哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))

if (elem) { // or !elem

or

if (typeof elem !== 'undefined') {

or

if (elem != null) {

当前回答

我很惊讶这还没有被提及。。。

以下是使用此['var_name']的一些其他变体

使用此方法的好处是,它可以在定义变量之前使用。

if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
if (this['elem'] !== undefined) {...}; // check if it's been declared
if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part

// these will work even if you have an improper variable definition declared here
elem = null; // <-- no var here!! BAD!

其他回答

我想要类似的东西:一个检查变量是否有有用值的函数,其中0是有用的,但空字符串、数组和对象不是(对于我的应用程序)。基于各种答案和评论,我提出了下面定义和测试的isSet()函数;对于测试值的前一半返回true,对于第二部分返回false,这正是我想要和需要的:

let fn = [1234, "1234", 0, "0", [1,2], {name: "number"}, "", [], {}, null, NaN, undefined]

console.log(fn)
const isSet = (val) => {
    switch (typeof val) {
        case 'number': return !isNaN(val); break; // as long as it is a number other than NaN....
        case 'string': return val.length > 0; break;
        case 'undefined': return false; break;
        case 'object':
            if (val === null) return false;
            else return Object.keys(val).length > 0;
            break;
    }
}

for (index in fn) {
    const item = fn[index];
    console.log(`ind: ${index}; ${typeof item}; ${isSet(item)}`)
}

结果(在节点v16.16.0下):

[
  1234,
  '1234',
  0,
  '0',
  [ 1, 2 ],
  { name: 'number' },
  '',
  [],
  {},
  null,
  NaN,
  undefined
]
ind: 0; number; true
ind: 1; string; true
ind: 2; number; true
ind: 3; string; true
ind: 4; object; true
ind: 5; object; true
ind: 6; string; false
ind: 7; object; false
ind: 8; object; false
ind: 9; object; false
ind: 10; number; false
ind: 11; undefined; false

为了使if条件正确工作,我们必须使用关键字let来创建变量。

let name = undefined; 
if (name) { 
    alert('valid')
};

我更喜欢这种方法,因为它的准确性和简洁性:

变量x如果(x===无效0){console.log(“x未定义”)}其他{console.log(“x已定义”)}

正如在其他评论和回答中提到的,undefined不能保证是undefineed。因为它不是关键字,所以可以在全局范围以外的范围中将其重新定义为变量。这里有一个小例子可以说明这种细微差别:

var undefined='bar'console.log(`在全局范围内:${undefined}`)函数foo(){var undefined=“已定义”变量x如果(x===未定义){console.log(`x===undefined`)}其他{console.log(`x!==undefined`)}如果(x===无效0){console.log(`x===void 0`)}其他{console.log(`x!==void 0`)}}foo()

请参阅void以了解兼容性(IE5支持!?!!哇!)。

我的首选是typeof(elem)!='未定义'&&elem!=无效的

无论您选择什么,请考虑将检查放入这样的函数中

function existy (x) {
    return typeof (x) != 'undefined' && x != null;
}

如果您不知道变量已声明,请继续使用typeof(x)!='未定义'&&x!=无效的

如果您知道变量已声明但可能不存在,可以使用

existy(elem) && doSomething(elem);

您正在检查的变量有时可能是嵌套属性。您可以使用prop | |{}来检查问题属性的存在性:

var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;

在每个属性之后,使用(…“| |{}”).nexPro,以便丢失的属性不会引发错误。

或者,您可以使用existy,如existy(o)&&exist(o.p)&&existiny(o.p.q)&&doSomething(o.p.q)

在ReactJS中,事情有点复杂!这是因为它是一个编译环境,遵循ESLint的无undef规则,因为react-scripts@2.0.3(2018年10月1日发布)。这里的文档对任何对此问题感兴趣的人都有帮助。。。

在JavaScript中,在ES6之前,变量和函数声明被提升到作用域的顶部,因此可以在代码中的正式声明之前使用标识符。。。。当ES6的[新]规则遇到对尚未声明的标识符的引用时,将发出警告。

因此,虽然有可能有一个未定义(或“未初始化”)的变量,但在ReactJS中有一个没有关闭esint规则的未声明变量是不可能的。

这可能非常令人沮丧——GitHub上有太多的项目只是利用了ES6之前的标准;并且在没有任何调整的情况下直接编译这些基本上是不可能的。

但是,对于ReactJS,可以使用eval()。如果你有一个未声明的变量,比如。。。

if(undeclaredvar) {...}

您可以简单地将此部分重写为。。。

if(eval('typeof undeclaredvar !== "undefined"')) {...}

例如。。。

if(eval(“false”)){console.log(“否!”);}if(eval(“true”)){console.log(“是!”);}

对于那些将GitHub存储库导入ReactJS项目的人来说,这只是检查是否声明了变量的唯一方法。在结束之前,我想提醒您,如果使用错误,eval()存在安全问题。