javascript - 在函数中有 (typeof !== 'undefined') 的解决方案吗?
问题描述
我想创建一个箭头函数来检查我的变量或值,但我不知道如何解决这个问题。在普通表达式(函数外)中它是有效的,但在函数中,在条件之前检查值并返回错误。有办法忽略或删除类似于 PHP 中的“@”的错误吗?
//the function:
var isValid = value => typeof value !== 'undefined' && value ? true : false;
如何工作:
var isValid = value => typeof value !== 'undefined' && value ? true : false;
var is_exists = 1;
console.log('//normal expression test with existing variable:');
console.log(typeof is_exists !== 'undefined' && is_exists ? true : false);
console.log('//normal expression test with nonexistent variable:');
console.log(typeof is_noexists !== 'undefined' && is_noexists ? true : false);
console.log('//arrow function test with existing variable:');
console.log(isValid(is_exists));
console.log('//arrow function test with noexisting variable:');
console.log(isValid(is_noexists));
注意:条件可以简化为typeof value !== 'undefined' && !!value
解决方案
对于一般情况,这是不可能的,至少不是以任何合理的方式。
当您将参数传递给函数时,解释器必须能够在函数内部的任何内容运行之前提取参数在该点包含的值。如果someVar
从未定义过,除非您typeof
先进行检查,否则您无法引用它。因此,您尝试实现的逻辑无法抽象为单独的函数;您必须在每次函数调用之前检查变量是否在调用站点定义。
也就是说,这是一个奇怪的问题。动态变量名称很奇怪,在大多数情况下应避免使用。如果您发现自己不得不做这样的事情,请考虑是否有可能以不同的方式构造您的数据,例如将可能存在的值放入单个对象中,例如:
const obj = {
value1: 'foo
};
// dynamically added property:
obj.value2 = 'bar';
// ...
console.log(Boolean(obj.value1));
console.log(Boolean(obj.value2));
这样,即使里面的属性obj
可以动态变化,唯一的变量名——the——obj
保持不变。这种模式更容易管理。
推荐阅读
- javascript - 为 JS 文档指定 errorpage.html.getElementById('link_id').value + '.html'; 如果在目录中找不到值?
- php - 如何将多个数组转换为 1 个标准?
- python - 如何在熊猫的groupby中重命名聚合列
- javascript - 由 PHP 生成的可扩展 HTML 表
- python - AWS Rekognition 和 s3 在 Python Lambda 中调用子文件夹
- bash - 在 bash 终端中使重要文件具有不同的颜色
- git - Git:编辑帅哥失败(当文件有其他帅哥时?)
- oracle - PL\SQL - OWA_UTIL.REDIRECT_URL 在新选项卡中打开
- android - 如何解决错误:编译'com.android.support:appcompat-v7:23.4.0'
- mysql - MySql 查询以加入在表之间以不同方式存储的 uuid