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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

很难区分undefined和null。Null是一个值,当您想要指示变量没有特定值时,可以将其赋值给该变量。未定义是一个特殊值,它将是未分配变量的默认值。


var _undefined;
var _null = null;

alert(_undefined); 
alert(_null); 
alert(_undefined == _null);
alert(_undefined === _null);

其他回答

if (typeof console != "undefined") {    
   ...
}

或者更好

if ((typeof console == "object") && (typeof console.profile == "function")) {    
   console.profile(f.constructor);    
}

适用于所有浏览器

当您执行简单的作业和相关检查时,还有另一种简便的方法来检查这一点。只需使用条件(三元)运算符。

var values = typeof variable !== 'undefined' ? variable : '';

当您尝试使用引用变量的实例赋值来声明全局变量时,这也会很有用。

若你们想检查变量不应该是未定义的或空的。然后执行以下检查。

当声明变量时,如果您想检查值,这甚至很简单:它将同时执行未定义和空检查。

var values = variable ? variable : '';

我想要类似的东西:一个检查变量是否有有用值的函数,其中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')
};

您需要运算符的类型。明确地:

if (typeof variable !== 'undefined') {
    // the variable is defined
}