Checking if a key exists in a JavaScript object?

前端 未结 22 2240
礼貌的吻别
礼貌的吻别 2020-11-21 22:57

How do I check if a particular key exists in a JavaScript object or array?

If a key doesn\'t exist, and I try to access it, will it return false? Or throw an error?<

22条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 23:29

    It will return undefined.

    var aa = {hello: "world"};
    alert( aa["hello"] );      // popup box with "world"
    alert( aa["goodbye"] );    // popup box with "undefined"

    undefined is a special constant value. So you can say, e.g.

    // note the three equal signs so that null won't be equal to undefined
    if( aa["goodbye"] === undefined ) {
        // do something
    }
    

    This is probably the best way to check for missing keys. However, as is pointed out in a comment below, it's theoretically possible that you'd want to have the actual value be undefined. I've never needed to do this and can't think of a reason offhand why I'd ever want to, but just for the sake of completeness, you can use the in operator

    // this works even if you have {"goodbye": undefined}
    if( "goodbye" in aa ) {
        // do something
    }
    

提交回复
热议问题