Javascript array value is undefined ... how do I test for that

This question already has an answer here:

  • JavaScript check if variable exists (is defined/initialized) 28 answers

  • array[index] == 'undefined' compares the value of the array index to the string "undefined".
    You're probably looking for typeof array[index] == 'undefined' , which compares the type.


    You are checking it the array index contains a string "undefined" , you should either use the typeof operator:

    typeof predQuery[preId] == 'undefined'
    

    Or use the undefined global property:

    predQuery[preId] === undefined
    

    The first way is safer, because the undefined global property is writable, and it can be changed to any other value.


    predQuery[preId]=='undefined'
    

    You're testing against the string 'undefined' ; you've confused this test with the typeof test which would return a string. You probably mean to be testing against the special value undefined :

    predQuery[preId]===undefined
    

    Note the strict-equality operator to avoid the generally-unwanted match null==undefined .

    However there are two ways you can get an undefined value: either preId isn't a member of predQuery , or it is a member but has a value set to the special undefined value. Often, you only want to check whether it's present or not; in that case the in operator is more appropriate:

    !(preId in predQuery)
    
    链接地址: http://www.djcxy.com/p/95004.html

    上一篇: 检查变量是否未定义不起作用

    下一篇: Javascript数组的值是未定义的...我该如何测试