Detecting an undefined object property

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

    Here is my situation:

    I am using the result of a REST call. The result should be parsed from JSON to a JavaScript object.

    There is one error I need to defend. If the arguments to the REST call were incorrect as far as the user specifying the arguments wrong, the REST call comes back basically empty.

    While using this post to help me defend against this, I tried this:

    if( typeof restResult.data[0] === "undefined" ) { throw  "Some error"; }
    

    For my situation, if restResult.data[0] === "object", then I can safely start inspecting the rest of the members. If undefined then throw the error as above.

    What I am saying is that for my situation, all the previous suggestions in this post did not work. I'm not saying I'm right and everyone is wrong. I am not a JavaScript master at all, but hopefully this will help someone.

提交回复
热议问题