Detecting an undefined object property

后端 未结 30 2944
花落未央
花落未央 2020-11-21 04:43

What\'s the best way of checking if an object property in JavaScript is undefined?

30条回答
  •  无人及你
    2020-11-21 05:43

    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)
    

    Object properties should work the same way.

    var person = {
        name: "John",
        age: 28,
        sex: "male"
    };
    
    alert(person.name); // "John"
    alert(person.fakeVariable); // undefined
    

提交回复
热议问题