Test if something is not undefined in JavaScript

前端 未结 11 1839
礼貌的吻别
礼貌的吻别 2020-11-30 19:50

I\'m checking if(response[0].title !== undefined), but I get the error:

Uncaught TypeError: Cannot read property \'title\' of undefined.<

11条回答
  •  孤独总比滥情好
    2020-11-30 20:11

    In some of these answers there is a fundamental misunderstanding about how to use typeof.

    Incorrect

    if (typeof myVar === undefined) {
    

    Correct

    if (typeof myVar === 'undefined') {
    

    The reason is that typeof returns a string. Therefore, you should be checking that it returned the string "undefined" rather than undefined (not enclosed in quotation marks), which is itself one of JavaScript's primitive types. The typeof operator will never return a value of type undefined.


    Addendum

    Your code might technically work if you use the incorrect comparison, but probably not for the reason you think. There is no preexisting undefined variable in JavaScript - it's not some sort of magic keyword you can compare things to. You can actually create a variable called undefined and give it any value you like.

    let undefined = 42;
    

    And here is an example of how you can use this to prove the first method is incorrect:

    https://jsfiddle.net/p6zha5dm/

提交回复
热议问题