哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
当前回答
最高答案是正确的,请使用typeof。
然而,我想指出的是,在JavaScript中,undefined是可变的(出于某种不道德的原因)。所以只需检查varName!==undefined有可能不会总是像您期望的那样返回,因为其他库可能已经更改了undefineed。一些答案(比如@skalee's)似乎更倾向于不使用typeof,这可能会让人陷入麻烦。
处理此问题的“旧”方法是将undefined声明为一个var,以抵消任何潜在的undefined/override。然而,最好的方法仍然是使用typeof,因为它将忽略其他代码中对undefined的任何重写。特别是如果你正在编写代码,以供在野外使用,谁知道页面上还有什么其他内容。。。
其他回答
为了使if条件正确工作,我们必须使用关键字let来创建变量。
let name = undefined;
if (name) {
alert('valid')
};
您需要运算符的类型。明确地:
if (typeof variable !== 'undefined') {
// the variable is defined
}
我更喜欢这种方法,因为它的准确性和简洁性:
变量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支持!?!!哇!)。
我想要类似的东西:一个检查变量是否有有用值的函数,其中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
这取决于您是否只关心变量是否已定义,或者是否希望它具有有意义的值。
检查类型是否未定义将检查变量是否已定义。
==空或!==null将仅检查变量的值是否完全为null。
==空或!=null将检查该值是否未定义或为null。
if(value)将检查变量是否为undefined、null、0或空字符串。