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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

这取决于情况。如果您正在检查代码之外可能或可能尚未全局定义的内容(例如jQuery),您需要:

if (typeof(jQuery) != "undefined")

(这里不需要严格相等,typeof总是返回字符串。)但是,如果函数的参数可能已传递,也可能未传递,则它们将始终被定义,但如果忽略,则为null。

function sayHello(name) {
    if (name) return "Hello, " + name;
    else return "Hello unknown person";
}
sayHello(); // => "Hello unknown person"

其他回答

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

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

您可以使用typeof运算符。

例如

var dataSet;

alert("Variable dataSet is : " + typeof dataSet);

上面的代码段将返回如下输出

变量dataSet为:undefined。

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

我的首选是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)

Null是JavaScript中的值,typeof Null返回“object”

因此,如果您传递空值,则接受的答案将不起作用。如果传递空值,则需要为空值添加额外的检查:

if ((typeof variable !== "undefined") && (variable !== null))  
{
   // the variable is defined and not null
}