Detecting an undefined object property

后端 未结 30 3609
花落未央
花落未央 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:36

    I use if (this.variable) to test if it is defined. A simple if (variable), recommended in a previous answer, fails for me.

    It turns out that it works only when a variable is a field of some object, obj.someField to check if it is defined in the dictionary. But we can use this or window as the dictionary object since any variable is a field in the current window, as I understand it. Therefore here is a test:

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

    It first detects that variable abc is undefined and it is defined after initialization.

提交回复
热议问题