哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、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的任何重写。特别是如果你正在编写代码,以供在野外使用,谁知道页面上还有什么其他内容。。。

其他回答

这些答案(除了Fred Gandt解决方案)要么不正确,要么不完整。

假设我需要我的variableName;携带一个未定义的值,因此它是以var variableName等方式声明的;这意味着它已经初始化;-如何检查是否已申报?

或者更好——我如何立即检查“Book1.chapter22.paragraph37”是否存在一次调用,但不会引起引用错误?

我们通过使用最强大的JasvaScript运算符in运算符来实现

"[variable||property]" in [context||root] 
>> true||false

我想要类似的东西:一个检查变量是否有有用值的函数,其中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(!variable),所以检查它是否是假的。这可以带来更干净的代码,例如:

if(数据类型!==“undefined”&&数据类型。url===“未定义”){var message='接收响应时出错';if(typeof data.error!==“undefined”){message=数据错误;}否则如果(数据类型.消息!==“未定义”){message=数据消息;}警报(消息);}

..可以简化为:

if(data&&!data.url){var message=data.error | | data.message | |'接收响应时出错';警报(消息)}

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

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

我根据对象使用两种不同的方式。

if( !variable ){
  // variable is either
  // 1. '';
  // 2. 0;
  // 3. undefined;
  // 4. null;
  // 5. false;
}

有时我不想将空字符串求值为false,所以我使用这种情况

function invalid( item ){
  return (item === undefined || item === null);
}

if( invalid( variable )){
  // only here if null or undefined;
}

如果你需要相反的东西,那么首先!变量变为!!变量,并且在无效函数中==变为!=函数名变为notInvalid。