检测未定义的对象属性

时间:2008-08-26 07:25:08

标签: javascript object undefined

检查JavaScript中的对象属性是否未定义的最佳方法是什么?

48 个答案:

答案 0 :(得分:2495)

使用:

if (typeof something === "undefined") {
    alert("something is undefined");
}

如果具有某些属性的对象变量可以使用相同的东西:

if (typeof my_obj.someproperties === "undefined"){
    console.log('the property is not available...'); // print into console
}

答案 1 :(得分:853)

我相信这个话题有很多不正确的答案。与普遍看法相反,“未定义”在JavaScript中是关键字,实际上可以为其分配值。

正确代码

执行此测试的最有效方法是:

if (typeof myVar === "undefined")

这将始终返回正确的结果,甚至可以处理未声明myVar的情况。

退化代码。不要使用。

var undefined = false;  // Shockingly, this is completely legal!
if (myVar === undefined) {
    alert("You have been misled. Run away!");
}

此外,myVar === undefined会在myVar未声明的情况下引发错误。

答案 2 :(得分:180)

尽管这里的许多其他答案强烈推荐,typeof 是一个糟糕的选择。它永远不应该用于检查变量是否具有值undefined,因为它充当值undefined的组合检查以及变量是否存在。在绝大多数情况下,您知道变量何时存在,如果您在变量名称或字符串文字typeof中输入错误,'undefined'将仅引入静默失败的可能性。 / p>

var snapshot = …;

if (typeof snaposhot === 'undefined') {
    //         ^
    // misspelled¹ – this will never run, but it won’t throw an error!
}
var foo = …;

if (typeof foo === 'undefned') {
    //                   ^
    // misspelled – this will never run, but it won’t throw an error!
}

因此,除非你正在进行特征检测²,否则给定名称是否在范围内是不确定的(比如将typeof module !== 'undefined'视为特定于CommonJS环境的代码中的一步),typeof是一个在变量上使用时有害的选择,正确的选择是直接比较值:

var foo = …;

if (foo === undefined) {
    ⋮
}

对此有一些常见的误解包括:

  • 读取“未初始化”变量(var foo)或参数(function bar(foo) { … },称为bar())将失败。这根本不是真的 - 没有显式初始化的变量和未给定值的参数总是变为undefined,并且始终在范围内。

  • 可以覆盖undefined。这还有更多。 undefined不是JavaScript中的关键字。相反,它是具有Undefined值的全局对象上的属性。但是,自ES5以来,此属性一直是只读不可配置。没有现代浏览器允许更改undefined属性,截至2017年,这种情况已经存在很长时间了。缺乏严格模式也不会影响undefined的行为 - 它只会使undefined = 5这样的语句不做任何事情而不是抛出。但是,由于它不是关键字,您可以声明名称为undefined的变量,并且可以更改这些变量,从而形成这种曾经常见的模式:

    (function (undefined) {
        // …
    })()
    

    更多比使用全局undefined更危险。如果您必须与ES3兼容,请将undefined替换为void 0 - 不要诉诸typeof。 (void一直是一元运算符,计算任何操作数的Undefined值。)

关于变量如何解决问题,是时候解决实际问题了:对象属性。没有理由将typeof用于对象属性。关于特征检测的早期例外在这里不适用 - typeof仅对变量有特殊行为,而引用对象属性的表达式不是变量。

此:

if (typeof foo.bar === 'undefined') {
    ⋮
}

总是完全等同于到这个:

if (foo.bar === undefined) {
    ⋮
}

并考虑上述建议,以避免让读者误解您使用typeof的原因,因为使用===检查相等性是最有意义的,因为它可能是重构后来检查变量的值,并且因为它看起来更好,你应该总是在这里使用=== undefined³

对于对象属性,还需要考虑的是你是否真的想要检查undefined。对象上可以不存在给定的属性名称(在读取时生成值undefined),在对象本身上显示值undefined,在对象的原型上显示值undefined ,或出现在具有非undefined值的任何一个上。 'key' in obj将告诉您密钥是否在对象的原型链上的任何位置,Object.prototype.hasOwnProperty.call(obj, 'key')将告诉您它是否直接在对象上。我不会在这个关于原型和使用对象作为字符串键映射的答案中详细说明,因为它主要是为了对抗其他答案中的所有不良建议,而不管原始问题的可能解释。阅读object prototypes on MDN了解更多信息!

¹示例变量名称的异常选择?这是来自Firefox的NoScript扩展的真正死代码。
不过,²并不认为不知道范围内的内容是否正常。滥用动态范围造成的奖励漏洞:Project Zero 1225
³再次假设ES5 +环境,undefined引用全局对象的undefined属性。否则替换void 0

答案 3 :(得分:146)

在JavaScript中有 null ,并且未定义。它们有不同的含义。

  • undefined 表示尚未定义变量值;不知道它的价值是什么。
  • null 表示定义变量值并设置为null(没有值)。

Marijn Haverbeke在他的免费在线书“Eloquent JavaScript”(强调我的)中说:

  

还有一个类似的值null,其含义是'此值已定义,但它没有值'。 undefined和null之间的意义差异主要是学术性的,通常不是很有趣。 在实际程序中,通常需要检查某些东西是否“有价值”。在这些情况下,可以使用表达式== undefined,因为即使它们不是完全相同的值,null == undefined也会生成true。

所以,我想检查某些内容是否未定义的最佳方法是:

if (something == undefined)

希望这有帮助!

编辑:为了响应您的编辑,对象属性应该以相同的方式工作。

var person = {
    name: "John",
    age: 28,
    sex: "male"
};

alert(person.name); // "John"
alert(person.fakeVariable); // undefined

答案 4 :(得分:114)

这是什么意思:“未定义的对象属性”

实际上它可能意味着两件完全不同的东西!首先,它可能意味着对象中从未定义的属性,其次,它可能意味着具有未定义值的属性。我们来看看这段代码:

var o = { a: undefined }

o.a未定义吗?是!它的价值是不确定的。 o.b未定义吗?当然!根本没有属性'b'!好的,现在看看两种情况下不同方法的表现如何:

typeof o.a == 'undefined' // true
typeof o.b == 'undefined' // true
o.a === undefined // true
o.b === undefined // true
'a' in o // true
'b' in o // false

我们可以清楚地看到typeof obj.prop == 'undefined'obj.prop === undefined是等价的,并且它们不区分这些不同的情况。并且'prop' in obj可以检测到根本没有定义属性的情况,并且不会注意可能未定义的属性值。

那该怎么办?

1)您想知道某个属性是否由第一个或第二个含义(最典型的情况)定义。

obj.prop === undefined // IMHO, see "final fight" below

2)你想知道对象是否有某些属性而不关心它的值。

'prop' in obj

说明:

  • 您无法同时检查对象及其属性。例如,如果未定义x,则此x.a === undefined或此typeof x.a == 'undefined'会引发ReferenceError: x is not defined
  • 变量undefined是一个全局变量(实际上它在浏览器中是window.undefined)。它自ECMAScript第1版以来一直受到支持,自ECMAScript 5以来它只有只读。因此,在现代浏览器中,它不能被重新定义为真正的,因为许多作者都喜欢吓唬我们,但对于旧浏览器来说仍然如此。

最后的战斗:obj.prop === undefined vs typeof obj.prop == 'undefined'

成群obj.prop === undefined

  • 它有点短,看起来更漂亮
  • 如果拼写错误undefined
  • ,JavaScript引擎会给您一个错误

obj.prop === undefined的错误:

  • undefined可以在旧浏览器中覆盖

成群typeof obj.prop == 'undefined'

  • 真的很普遍!它适用于新旧浏览器。

typeof obj.prop == 'undefined'的错误:

  • 'undefned'拼写错误的)这里只是一个字符串常量,所以如果你像我刚才那样拼错了它,JavaScript引擎就无法帮助你。

更新(对于服务器端JavaScript):

Node.js支持全局变量undefinedglobal.undefined(它也可以在没有'global'前缀的情况下使用)。我不知道服务器端JavaScript的其他实现。

答案 5 :(得分:63)

问题可归结为三种情况:

  1. 该对象具有该属性,其值不是undefined
  2. 该对象具有该属性,其值为undefined
  3. 该对象没有该属性。
  4. 这告诉我们一些我认为重要的事情:

    未定义的成员与具有未定义值的已定义成员之间存在差异。

    但不幸的是typeof obj.foo并没有告诉我们我们拥有的三个案例中的哪一个。但是,我们可以将其与"foo" in obj结合起来区分案例。

                                   |  typeof obj.x === 'undefined' | !("x" in obj)
    1.                     { x:1 } |  false                        | false
    2.    { x : (function(){})() } |  true                         | false
    3.                          {} |  true                         | true
    

    值得注意的是,null条目的这些测试也是相同的

                                   |  typeof obj.x === 'undefined' | !("x" in obj)
                        { x:null } |  false                        | false
    

    我认为在某些情况下检查属性是否存在更有意义(并且更清楚),而不是检查它是否未定义,并且唯一的情况是此检查将是不同的是案例2,在具有未定义值的对象中实际输入的罕见情况。

    例如:我刚刚重构了一堆代码,这些代码检查对象是否具有给定属性。

    if( typeof blob.x != 'undefined' ) {  fn(blob.x); }
    

    在没有检查未定义的情况下编写时更清楚。

    if( "x" in blob ) { fn(blob.x); }
    

    但正如已经提到的,这些并不完全相同(但对我的需求来说已经足够好了)。

答案 6 :(得分:41)

if ( typeof( something ) == "undefined") 

这对我有用,而其他人没有。

答案 7 :(得分:37)

我不确定===typeof一起使用的来源在哪里,作为一种惯例,我看到它在许多库中使用,但是typeof运算符返回一个字符串文字,我们事先知道,所以你为什么还要打字呢?

typeof x;                      // some string literal "string", "object", "undefined"
if (typeof x === "string") {   // === is redundant because we already know typeof returns a string literal
if (typeof x == "string") {    // sufficient

答案 8 :(得分:22)

从相关问题answer

中截取我的How to check for "undefined" in JavaScript?

针对此问题,请参阅someObject.<whatever>的测试用例。


一些场景说明了各种答案的结果: http://jsfiddle.net/drzaus/UVjM4/

(请注意,在var测试中使用in会在作用域包装中产生影响

参考代码:

(function(undefined) {
    var definedButNotInitialized;
    definedAndInitialized = 3;
    someObject = {
        firstProp: "1"
        , secondProp: false
        // , undefinedProp not defined
    }
    // var notDefined;

    var tests = [
        'definedButNotInitialized in window',
        'definedAndInitialized in window',
        'someObject.firstProp in window',
        'someObject.secondProp in window',
        'someObject.undefinedProp in window',
        'notDefined in window',

        '"definedButNotInitialized" in window',
        '"definedAndInitialized" in window',
        '"someObject.firstProp" in window',
        '"someObject.secondProp" in window',
        '"someObject.undefinedProp" in window',
        '"notDefined" in window',

        'typeof definedButNotInitialized == "undefined"',
        'typeof definedButNotInitialized === typeof undefined',
        'definedButNotInitialized === undefined',
        '! definedButNotInitialized',
        '!! definedButNotInitialized',

        'typeof definedAndInitialized == "undefined"',
        'typeof definedAndInitialized === typeof undefined',
        'definedAndInitialized === undefined',
        '! definedAndInitialized',
        '!! definedAndInitialized',

        'typeof someObject.firstProp == "undefined"',
        'typeof someObject.firstProp === typeof undefined',
        'someObject.firstProp === undefined',
        '! someObject.firstProp',
        '!! someObject.firstProp',

        'typeof someObject.secondProp == "undefined"',
        'typeof someObject.secondProp === typeof undefined',
        'someObject.secondProp === undefined',
        '! someObject.secondProp',
        '!! someObject.secondProp',

        'typeof someObject.undefinedProp == "undefined"',
        'typeof someObject.undefinedProp === typeof undefined',
        'someObject.undefinedProp === undefined',
        '! someObject.undefinedProp',
        '!! someObject.undefinedProp',

        'typeof notDefined == "undefined"',
        'typeof notDefined === typeof undefined',
        'notDefined === undefined',
        '! notDefined',
        '!! notDefined'
    ];

    var output = document.getElementById('results');
    var result = '';
    for(var t in tests) {
        if( !tests.hasOwnProperty(t) ) continue; // bleh

        try {
            result = eval(tests[t]);
        } catch(ex) {
            result = 'Exception--' + ex;
        }
        console.log(tests[t], result);
        output.innerHTML += "\n" + tests[t] + ": " + result;
    }
})();

结果:

definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined

答案 9 :(得分:17)

如果你这样做

if (myvar == undefined )
{ 
    alert('var does not exists or is not initialized');
}

当变量myvar不存在时,它将失败,因为myvar未定义,因此脚本被破坏且测试无效。

因为窗口对象在函数外部具有全局范围(默认对象),所以声明将“附加”到窗口对象。

例如:

var myvar = 'test';

全局变量 myvar window.myvar window ['myvar']

相同

为了避免在存在全局变量时测试错误,最好使用:

if(window.myvar == undefined )
{ 
    alert('var does not exists or is not initialized');
}

变量确实存在的问题无关紧要,其值不正确。否则,使用undefined初始化变量是愚蠢的,最好使用值false来初始化。当您知道所声明的所有变量都使用false初始化时,您只需检查其类型或依赖!window.myvar检查它是否具有正确/有效值。因此,即使未定义变量,!window.myvarmyvar = undefinedmyvar = false的{​​{1}}也相同。

当您需要特定类型时,请测试变量的类型。为了加快测试条件,你最好这样做:

myvar = 0

当第一个和简单条件为真时,解释器会跳过下一个测试。

最好使用变量的实例/对象来检查它是否有有效值。它更稳定,是一种更好的编程方式。

(y)的

答案 10 :(得分:16)

我没有看到(希望我没有错过)任何人在物业前检查物品。因此,这是最短且最有效的(尽管不一定是最清楚的):

if (obj && obj.prop) {
  // Do something;
}

如果obj或obj.prop未定义,null或“falsy”,则if语句将不执行代码块。这通常是大多数代码块语句中的所需行为(在JavaScript中)。

答案 11 :(得分:13)

在文章 Exploring the Abyss of Null and Undefined in JavaScript 中,我读到像Underscore.js这样的框架使用此函数:

function isUndefined(obj){
    return obj === void 0;
}

答案 12 :(得分:11)

' if(window.x){} '是错误安全的

您最有可能想要if (window.x)。即使未声明x(var x;),此检查也是安全的 - 浏览器不会抛出错误。

示例:我想知道我的浏览器是否支持History API

if (window.history) {
    history.call_some_function();
}

如何运作:

窗口是一个将所有全局变量保存为其成员的对象,尝试访问不存在的成员是合法的。如果 x 尚未声明或尚未设置,则window.x会返回未定义。当 if()对其进行评估时, undefined 会导致 false

答案 13 :(得分:10)

通过阅读,我很惊讶我没有看到这一点。我找到了多种适用于此的算法。

从未定义

如果从未定义过对象的值,如果将其定义为truenull,则会阻止返回undefined。如果您希望为设置为undefined

的值返回true,这将非常有用
if(obj.prop === void 0) console.log("The value has never been defined");

定义为未定义或永不定义

如果您希望以trueundefined来定义值为=== undefined或从未定义的值,则只需使用if(obj.prop === undefined) console.log("The value is defined as undefined, or never defined");

undefined

定义为假值,未定义,空或永不定义。

通常,人们会问我一个算法,以确定某个值是假,null还是if(obj.prop == false || obj.prop === null || obj.prop === undefined) { console.log("The value is falsy, null, or undefined"); } 。以下作品。

{{1}}

答案 14 :(得分:10)

"propertyName" in obj //-> true | false

答案 15 :(得分:9)

您可以使用以下代码获取所有未定义的数组。

 function getAllUndefined(object) {

        function convertPath(arr, key) {
            var path = "";
            for (var i = 1; i < arr.length; i++) {

                path += arr[i] + "->";
            }
            path += key;
            return path;
        }


        var stack = [];
        var saveUndefined= [];
        function getUndefiend(obj, key) {

            var t = typeof obj;
            switch (t) {
                case "object":
                    if (t === null) {
                        return false;
                    }
                    break;
                case "string":
                case "number":
                case "boolean":
                case "null":
                    return false;
                default:
                    return true;
            }
            stack.push(key);
            for (k in obj) {
                if (obj.hasOwnProperty(k)) {
                    v = getUndefiend(obj[k], k);
                    if (v) {
                        saveUndefined.push(convertPath(stack, k));
                    }
                }
            }
            stack.pop();

        }

        getUndefiend({
            "": object
        }, "");
        return saveUndefined;
    }

jsFiddle链接

答案 16 :(得分:9)

JavaScript中没有定义任何内容,未定义,如果它是Object / Array中的属性或仅仅是一个简单的变量无关紧要......

JavaScript有typeof,这使得检测未定义的变量非常容易。

只需检查typeof whatever === 'undefined'是否会返回布尔值。

这就是AngularJs v.1x中着名函数isUndefined()的编写方式:

function isUndefined(value) {return typeof value === 'undefined';} 

因此,当您看到函数接收到值时,如果定义了该值,它将返回false,否则对于未定义的值,返回true

那么让我们来看看当我们传递值时会产生什么结果,包括下面的对象属性,这是我们拥有的变量列表:

var stackoverflow = {};
stackoverflow.javascipt = 'javascript';
var today;
var self = this;
var num = 8;
var list = [1, 2, 3, 4, 5];
var y = null;

我们将它们检查如下,你可以在它们前面看到结果作为评论:

isUndefined(stackoverflow); //false
isUndefined(stackoverflow.javascipt); //false
isUndefined(today); //true
isUndefined(self); //false
isUndefined(num); //false
isUndefined(list); //false
isUndefined(y); //false
isUndefined(stackoverflow.java); //true
isUndefined(stackoverflow.php); //true
isUndefined(stackoverflow && stackoverflow.css); //true

如您所见,我们可以在代码中使用类似的内容检查任何内容,如上所述,您只需在代码中使用typeof,但如果您反复使用它,请创建一个类似角度的函数我分享并继续重复使用的样本,如下面的DRY代码模式。

还有一件事,为了检查真实应用程序中的对象的属性,你甚至不确定对象是否存在,检查对象是否存在。

如果检查对象上的属性并且该对象不存在,则会抛出错误并停止整个应用程序的运行。

isUndefined(x.css);
VM808:2 Uncaught ReferenceError: x is not defined(…)

如此简单,你可以在if语句中包装如下:

if(typeof x !== 'undefined') {
  //do something
}

在Angular 1.x中也等于isDefined ......

function isDefined(value) {return typeof value !== 'undefined';}

其他javascript框架(如下划线)也有类似的定义检查,但如果您尚未使用任何框架,我建议您使用typeof

我还从MDN添加了这一部分,其中包含有关typeof,undefined和void(0)的有用信息。

  

严格相等和未定义
您可以使用undefined和严格相等和不等运算符来确定变量是否具有   一个值。在以下代码中,未定义变量x和   if语句的计算结果为true。

var x;
if (x === undefined) {
   // these statements execute
}
else {
   // these statements do not execute
}
  

注意:严格的相等运算符而不是标准的相等   必须在这里使用运算符,因为x == undefined也会检查是否   x为null,而严格相等则不为。 null不等于   未定义。有关详细信息,请参阅比较运算符。

  

Typeof运算符和undefined
  或者,可以使用typeof:

var x;
if (typeof x === 'undefined') {
   // these statements execute
}
  

使用typeof的一个原因是它不会抛出错误   变量尚未声明。

// x has not been declared before
if (typeof x === 'undefined') { // evaluates to true without errors
   // these statements execute
}

if (x === undefined) { // throws a ReferenceError

}
  

但是,应该避免这种技术。 JavaScript是一个   静态范围的语言,因此知道是否声明了变量   通过查看它是否在封闭的上下文中声明来阅读。该   唯一的例外是全局范围,但全局范围是必然的   全局对象,所以检查变量的存在   全局上下文可以通过检查属性的存在来完成   全局对象(例如,使用in运算符)。

  

无效操作符和未定义

     

虚空运算符是第三种选择。

var x;
if (x === void 0) {
   // these statements execute
}

// y has not been declared before
if (y === void 0) {
   // throws a ReferenceError (in contrast to `typeof`)
}

更多&gt; here

答案 17 :(得分:8)

void 0比较,简洁。

if (foo !== void 0)

它不像if (typeof foo !== 'undefined')

那么冗长

答案 18 :(得分:8)

解决方案不正确。在JavaScript中,

null == undefined

将返回true,因为它们都被“转换”为布尔值并且为false。正确的方法是检查

if (something === undefined)

是身份运营商......

答案 19 :(得分:7)

有一个很好的&amp;如果已定义属性,则将定义的属性分配给新变量,或者如果未定义则将默认值指定为后备属性。

var a = obj.prop || defaultValue;

如果你有一个函数,它是合适的,它接收一个额外的配置属性:

var yourFunction = function(config){

   this.config = config || {};
   this.yourConfigValue = config.yourConfigValue || 1;
   console.log(this.yourConfigValue);

}

正在执行

yourFunction({yourConfigValue:2});
//=> 2

yourFunction();
//=> 1

yourFunction({otherProperty:5});
//=> 1

答案 20 :(得分:7)

以下是我的情况:

我正在使用REST调用的结果。 结果应该从JSON解析为JavaScript对象。

我需要保护一个错误。 如果用户指定args错误,那么其余调用的args是不正确的,其余的调用基本上都是空的。

在使用这篇文章来帮助我防范这一点时,我尝试了这个。

if( typeof restResult.data[0] === "undefined" ) { throw  "Some error"; }

对于我的情况,如果restResult.data [0] ===“object”,那么我可以安全地开始检查其余的成员。如果未定义,则抛出上述错误。

我所说的是,对于我的情况,本文上面的所有建议都不起作用。我不是说我是对的,每个人都错了。我根本不是JavaScript大师,但希望这会对某人有所帮助。

答案 21 :(得分:6)

所有答案都不完整。这是知道某个属性“定义为未定义”的正确方法:

var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){
  return ((prop in obj) && (typeof obj[prop] == 'undefined')) ;
} ;

示例:

var a = { b : 1, e : null } ;
a.c = a.d ;

hasUndefinedProperty(a, 'b') ; // false : b is defined as 1
hasUndefinedProperty(a, 'c') ; // true : c is defined as undefined
hasUndefinedProperty(a, 'd') ; // false : d is undefined
hasUndefinedProperty(a, 'e') ; // false : e is defined as null

// And now...
delete a.c ;
hasUndefinedProperty(a, 'c') ; // false : c is undefined

太糟糕了,这是正确的答案被埋没在错误的答案&gt; _&lt;

所以,对于任何经过的人,我都会免费给你一些未定义的东西!!

var undefined ; undefined ; // undefined
({}).a ;                    // undefined
[].a ;                      // undefined
''.a ;                      // undefined
(function(){}()) ;          // undefined
void(0) ;                   // undefined
eval() ;                    // undefined
1..a ;                      // undefined
/a/.a ;                     // undefined
(true).a ;                  // undefined

答案 22 :(得分:6)

通过评论,对于那些想要检查两者的人来说,它是未定义的还是其值为null:

//Just in JavaScript
var s; // Undefined
if (typeof s == "undefined" || s === null){
    alert('either it is undefined or value is null')
}

如果您使用的是jQuery Library,那么jQuery.isEmptyObject()就足以满足这两种情况,

var s; // Undefined
jQuery.isEmptyObject(s); // Will return true;

s = null; // Defined as null
jQuery.isEmptyObject(s); // Will return true;

//Usage
if (jQuery.isEmptyObject(s)) {
    alert('Either variable:s is undefined or its value is null');
} else {
     alert('variable:s has value ' + s);
}

s = 'something'; // Defined with some value
jQuery.isEmptyObject(s); // Will return false;

答案 23 :(得分:6)

如果您使用的是Angular:

angular.isUndefined(obj)
angular.isUndefined(obj.prop)

Underscore.js:

_.isUndefined(obj) 
_.isUndefined(obj.prop) 

答案 24 :(得分:6)

我使用if (this.variable)来测试它是否已定义。简单if (variable)recommended above对我来说失败了。事实证明,只有当变量是某个对象的字段obj.someField时才能检查它是否在字典中定义。但我们可以使用thiswindow作为字典对象,因为根据我的理解,任何变量都是当前窗口中的字段。因此这是一个测试

&#13;
&#13;
if (this.abc) alert("defined"); else alert("undefined");

abc = "abc";
if (this.abc) alert("defined"); else alert("undefined");
&#13;
&#13;
&#13;

它首先检测到变量abc未定义,并在初始化后定义。

答案 25 :(得分:4)

function isUnset(inp) {
  return (typeof inp === 'undefined')
}

如果设置了变量,则返回false;如果未定义,则返回true。

然后使用:

if (isUnset(var)) {
  // initialize variable here
}

答案 26 :(得分:3)

对于那些期待奇怪答案的人,我提供了三种方法:

function isUndefined1(val) {
    try {
        val.a;
    } catch (e) {
        return /undefined/.test(e.message);
    }
    return false;
}
function isUndefined2(val) {
    return !val && val+'' === 'undefined';
}
function isUndefined3(val) {
    const defaultVal={};
    return ((input=defaultVal)=>input===defaultVal)(val);
}
function test(func){
    console.group(`test start :`+func.name);
    console.log(func(undefined));
    console.log(func(null));
    console.log(func(1));
    console.log(func("1"));
    console.log(func(0));
    console.log(func({}));
    console.log(func(function () { }));
    console.groupEnd();
}
test(isUndefined1);
test(isUndefined2);
test(isUndefined3);

isUndefined1:

尝试获取输入值的属性,检查错误消息是否存在。如果输入值未定义,则错误消息为 Uncaught TypeError:无法读取未定义的属性“b”

isUndefined2:

将输入值转换为字符串以与"undefined"进行比较,并确保其为负值。

isUndefined3:

在js中,当输入值正好为undefined时,可选参数有效。

答案 27 :(得分:3)

我想向您展示一些我正在使用的内容,以保护undefined变量:

Object.defineProperty(window, 'undefined', {});

这禁止任何人更改window.undefined值,因此会根据该变量销毁代码。如果使用"use strict",任何试图更改其值的内容都将以错误结束,否则会被忽略。

答案 28 :(得分:3)

有一个非常简单的方法。

您可以使用可选链接

x = {prop:{name:"sajad"}}

console.log(x.prop?.name) // Output is: "sajad"
console.log(x.prop?.lastName) // Output is: undefined

if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error

您甚至可以为函数或数组使用可选链接。

截至2020年中,这尚未得到普遍实施。查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

上的文档

答案 29 :(得分:3)

来自lodash.js。

var undefined;
function isUndefined(value) {
  return value === undefined;
}

它创建一个名为undefined的LOCAL变量,该变量使用默认值 - 真实undefined进行初始化,然后将value与变量undefined进行比较。

答案 30 :(得分:3)

同样的事情可以写得更短:

if (!variable){
    //do it if variable is Undefined
}

if (variable){
    //do it if variable is Defined
}

答案 31 :(得分:2)

您也可以使用Proxy,它可以使用嵌套调用,但需要额外检查一次:

    <ProgressBar Minimum="0"
                 Maximum="100"
                 Height="10"
                 Value="{Binding MyProgress}">
        <ProgressBar.Resources>
            <Style TargetType="ProgressBar">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsError}"
                                 Value="True">
                        <Setter Property="Foreground"
                                Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ProgressBar.Resources>
    </ProgressBar>

因此您将使用它:

IsError

答案 32 :(得分:2)

ES2019引入了一项新功能-可选链接,仅当这样定义对象时,才可以使用它来使用对象的属性:

const userPhone = user?.contactDetails?.phone;

仅当定义了user和contactDetails时,它将引用电话属性。

参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

答案 33 :(得分:1)

我很惊讶我还没有看到这个建议,但它比使用typeof进行测试更具特异性。如果您需要知道对象属性是使用undefined初始化还是从未初始化,请使用Object.getOwnPropertyDescriptor()

// to test someObject.someProperty
var descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');

if (typeof descriptor === 'undefined') {
  // was never initialized
} else if (typeof descriptor.value === 'undefined') {
  if (descriptor.get || descriptor.set) {
    // is an accessor property, defined via getter and setter
  } else {
    // is initialized with `undefined`
  }
} else {
  // is initialized with some other value
}

答案 34 :(得分:1)

在最近的JavaScript版本中,引入了新的链接运算符,这很可能是检查属性是否存在的最佳方法,否则它将使您无法定义

请参见下面的示例

  const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

我们可以替换旧的语法

if (response && response.data && response.data.someData && response.data.someData.someMoreData) {}

使用这种更简洁的语法

if( response?.data?.someData?.someMoreData) {}

IE,Opera,safari和samsund android不支持此语法

有关更多详细信息,您可以检查此URL

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

答案 35 :(得分:0)

句柄未定义

function isUndefined(variable,defaultvalue=''){

    if (variable == undefined )
    { 
        return defaultvalue;
    }
    return variable

}

var obj={
und:undefined,
notundefined:'hi i am not undefined'
}


function isUndefined(variable,defaultvalue=''){

    if (variable == undefined )
    { 
        return defaultvalue;
    }
    return variable

}

console.log(isUndefined(obj.und,'i am print'))
console.log(isUndefined(obj.notundefined,'i am print'))

答案 36 :(得分:0)

动态变量的使用版本 你知道吗?

const extraState = this.router.getCurrentNavigation().extras.state;
        if (extraState && extraState.skipResolver) {
            return of(null);
        }

答案 37 :(得分:0)

评论

许多给出的答案给出了错误的结果,因为它们无法区分对象属性不存在的情况和属性值为undefined的情况。以下是最流行的解决方案的证明

let obj = {
  a: 666,
  u: undefined // The 'u' property has value 'undefined'
               // The 'x' property does not exist
}

console.log('>>> good results:');
console.log('A', "u" in obj, "x" in obj);
console.log('B', obj.hasOwnProperty("u"),      obj.hasOwnProperty("x"));

console.log('\n>>> bad results:');
console.log('C', obj.u === undefined,          obj.x === undefined);
console.log('D', obj.u == undefined,           obj.x == undefined);
console.log('E', obj["u"] === undefined,       obj["x"] === undefined);
console.log('F', obj["u"] == undefined,        obj["x"] == undefined);
console.log('G', !obj.u,                      !obj.x);
console.log('H', typeof obj.u === 'undefined', typeof obj.x === 'undefined');

答案 38 :(得分:0)

在JavaScript中,有真实虚假表达式。如果要检查属性是否未定义,可以直接使用给定的 if 条件

  1. 使用真实/虚假概念。
if(!ob.someProp){
    console.log('someProp is falsy')
}

但是,还有其他几种方法来检查对象是否具有属性,但是对我来说似乎很长。这些是这些。

  1. 使用 === undefined 签入 if 条件
if(ob.someProp === undefined){
    console.log('someProp is undefined')
}
  1. 使用 typeof

typeof 组合检查未定义的值和变量是否存在。

if(typeof ob.someProp === 'undefined'){
    console.log('someProp is undefined')
}
  1. 使用 hasOwnProperty 方法

JavaScript对象已在对象原型的hasOwnProperty函数中内置。

if(!ob.hasOwnProperty('someProp')){
    console.log('someProp is undefined')
}

不会深入,但是1 st 的方法看起来很短,对我也很有益。以下是JavaScript中truthy/falsy值的详细信息,其中undefined是其中列出的虚假值。因此,if条件的行为正常,没有任何故障。除了undefined,值NaNfalse(很明显),''(空字符串)和数字0也是伪造的值。

警告请确保属性值不包含任何虚假值,否则if条件将返回false。在这种情况下,您可以使用hasOwnProperty方法

答案 39 :(得分:0)

我发现这篇文章 7 Tips to Handle undefined in JavaScript 展示了关于undefined的一些非常有趣的事情 喜欢:

undefined的存在是JavaScript允许使用以下内容的结果:

  • 未初始化的变量
  • 不存在的对象属性或方法
  • 越界索引访问数组元素
  • 什么都不返回的函数的调用结果

答案 40 :(得分:0)

检查密钥是否存在的简单方法是使用in

if (key in obj) {
  // do something
} else {
  // create key
}

const obj = {
  0: 'abc',
  1: 'def'
}

const hasZero = 0 in obj

console.log(hasZero) // true

答案 41 :(得分:0)

ECMAScript 6 中引入,我们现在可以使用代理以新方式处理undefined。可以使用它为所有不存在的属性设置默认值,这样我们就不必每次都检查它是否确实存在。

var handler = {
  get: function(target, name) {
    return name in target ? target[name] : 'N/A';
  }
};

var p = new Proxy({}, handler);
p.name = 'Kevin';
console.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)

将输出以下文本,而不会得到任何未定义的内容。

Name: Kevin , Age: N/A , Gender: N/A

答案 42 :(得分:0)

lodash库中有一些小助手:

isUndefined - 检查是否为undefined

_.isUndefined(undefined) // => true
_.isUndefined(null) // => false

has - 检查对象是否包含属性

const object = { 'a': { 'b': 2 } }

_.has(object, 'a.b') // => true
_.has(object, 'a.c') // => false

答案 43 :(得分:0)

您可以像这样使用Javascript Object函数:

var ojb ={
    age:12
}

if(ojb.hasOwnProperty('name')){
    console.log('property exist and not undefined');
}

如果上述方法的属性或属性未定义,则返回true

答案 44 :(得分:0)

我假设您还要检查 undefinednull。如果是这样,我建议:

myVar == null

这是 double等于非常有用的时间之一,因为当truemyVar或{{1}时,它会评估为undefined },但如果是nullfalse0false等其他虚假值,则评估为''

这是Lodash的source方法的实际isNil代码。

答案 45 :(得分:0)

这可能是确定现有属性名称是否具有undefined的明确和预期值的唯一明确形式;尽管如此,这是一种JS类型。

"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";
>> true \ false

如果给定上下文的属性名称(确实)存在且仅当其预期值明确为true时,此表达式将仅返回undefined

没有误报,例如空字符串或空字符串零或空数组等。这正是如此。检查即,确保属性名称存在(否则它将是误报),而不是明确检查其值是否为undefined,例如未定义的JS类型在它的字符串表示形式(字面意思是“未定义”)因此==而不是===因为无法进一步转换。并且只有满足所有条件时,此表达式才会返回true。例如如果属性名称不存在,则返回false。这是唯一正确的返回,因为不存在的属性不能具有值,甚至不是未定义的值。

示例:

containerObject = { propertyName: void "anything" }
>> Object { propertyName: undefined } 

// now the testing

"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";
>> true

/* which makes sure that nonexistent property will not return a false positive
 * unless it is previously defined  */

"foo" in containerObject && ""+containerObject["foo"] == "undefined";
>> false

答案 46 :(得分:-2)

Object.hasOwnProperty(o, 'propertyname');

然而,这并没有通过原型链查找。

答案 47 :(得分:-16)

if (somevariable == undefined) {
  alert('the variable is not defined!');
}

你也可以把它变成一个函数,如here所示:

function isset(varname){
  return(typeof(window[varname]) != 'undefined');
}