Prevent error "is undefined" in if statement

This question already has an answer here:

  • Detecting an undefined object property 40 answers

  • && will return true only if both the values of ( a && b ) a and b are truthy values.

    If first operand( expression ) is evaluated as false , second operand( expression ) is not evaluated at all because the result would always be false


    is better practice to use typeof to evaluate undefined variables:

    if ( typeof array[index] !== 'undefined' && array[index].id == 1)
    {
       // code
    }
    

    Remember to check the string 'undefined' not the primitive value.

    More info in MDN


    No, if array is undefined, you will need an if statement that looks something like this:

    if (array && array[index] !== undefined && array[index].id === 1) {
       // do things
    }
    

    The first condition that if false will stop the evaluations of all the other conditions. The only way this will fail is if you are running you code in strict mode and have never declared var array

    链接地址: http://www.djcxy.com/p/22638.html

    上一篇: TypeError:undefined不是一个对象

    下一篇: 在if语句中防止错误“未定义”