Detecting an undefined object property

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

    If you do

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

    it will fail when the variable myvar does not exists, because myvar is not defined, so the script is broken and the test has no effect.

    Because the window object has a global scope (default object) outside a function, a declaration will be 'attached' to the window object.

    For example:

    var myvar = 'test';
    

    The global variable myvar is the same as window.myvar or window['myvar']

    To avoid errors to test when a global variable exists, you better use:

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

    The question if a variable really exists doesn't matter, its value is incorrect. Otherwise, it is silly to initialize variables with undefined, and it is better use the value false to initialize. When you know that all variables that you declare are initialized with false, you can simply check its type or rely on !window.myvar to check if it has a proper/valid value. So even when the variable is not defined then !window.myvar is the same for myvar = undefined or myvar = false or myvar = 0.

    When you expect a specific type, test the type of the variable. To speed up testing a condition you better do:

    if( !window.myvar || typeof window.myvar != 'string' )
    {
        alert('var does not exists or is not type of string');
    }
    

    When the first and simple condition is true, the interpreter skips the next tests.

    It is always better to use the instance/object of the variable to check if it got a valid value. It is more stable and is a better way of programming.

    (y)

提交回复
热议问题