首页 > 解决方案 > 在函数中有 (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

标签: javascript

解决方案


对于一般情况,这是不可能的,至少不是以任何合理的方式。

当您将参数传递给函数时,解释器必须能够在函数内部的任何内容运行之前提取参数在该点包含的值。如果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保持不变。这种模式更容易管理。


推荐阅读