Checking if a key exists in a JavaScript object?

前端 未结 22 2266
礼貌的吻别
礼貌的吻别 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:31

    These example can demonstrate the differences between defferent ways. Hope it will help you to pick the right one for your needs:

    // Lets create object `a` using create function `A`
    function A(){};
    A.prototype.onProtDef=2;
    A.prototype.onProtUndef=undefined;
    var a=new A();
    a.ownProp = 3;
    a.ownPropUndef = undefined;
    
    // Let's try different methods:
    
    a.onProtDef; // 2
    a.onProtUndef; // undefined
    a.ownProp; // 3
    a.ownPropUndef; // undefined
    a.whatEver; // undefined
    a.valueOf; // ƒ valueOf() { [native code] }
    
    a.hasOwnProperty('onProtDef'); // false
    a.hasOwnProperty('onProtUndef'); // false
    a.hasOwnProperty('ownProp'); // true
    a.hasOwnProperty('ownPropUndef'); // true
    a.hasOwnProperty('whatEver'); // false
    a.hasOwnProperty('valueOf'); // false
    
    'onProtDef' in a; // true
    'onProtUndef' in a; // true
    'ownProp' in a; // true
    'ownPropUndef' in a; // true
    'whatEver' in a; // false
    'valueOf' in a; // true (on the prototype chain - Object.valueOf)
    
    Object.keys(a); // ["ownProp", "ownPropUndef"]
    

提交回复
热议问题