Detecting an undefined object property

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


Use:

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

If an object variable which have some properties you can use same thing like this:

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

I believe there are a number of incorrect answers to this topic. Contrary to common belief, "undefined" is not a keyword in JavaScript and can in fact have a value assigned to it.

Correct Code

The most robust way to perform this test is:

if (typeof myVar === "undefined")

This will always return the correct result, and even handles the situation where myVar is not declared.

Degenerate code. DO NOT USE.

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

Additionally, myVar === undefined will raise an error in the situation where myVar is undeclared.


In JavaScript there is null and there is undefined . They have different meanings.

  • undefined means that the variable value has not been defined; it is not known what the value is.
  • null means that the variable value is defined and set to null (has no value).
  • Marijn Haverbeke states, in his free, online book "Eloquent JavaScript" (emphasis mine):

    There is also a similar value, null, whose meaning is 'this value is defined, but it does not have a value'. The difference in meaning between undefined and null is mostly academic, and usually not very interesting. In practical programs, it is often necessary to check whether something 'has a value'. In these cases, the expression something == undefined may be used, because, even though they are not exactly the same value, null == undefined will produce true.

    So, I guess the best way to check if something was undefined would be:

    if (something == undefined)
    

    Hope this helps!

    Edit: In response to your edit, object properties should work the same way.

    var person = {
        name: "John",
        age: 28,
        sex: "male"
    };
    
    alert(person.name); // "John"
    alert(person.fakeVariable); // undefined
    
    链接地址: http://www.djcxy.com/p/520.html

    上一篇: 使用Git版本控制查看文件的更改历史记录

    下一篇: 检测未定义的对象属性