如何检查JavaScript对象或数组中是否存在特定键?

如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?


当前回答

如果要检查对象上任何深度的任何键并考虑假值,请考虑实用函数的这一行:

var keyExistsOn = (o, k) => k.split(".").reduce((a, c) => a.hasOwnProperty(c) ? a[c] || 1 : false, Object.assign({}, o)) === false ? false : true;

后果

var obj = {
    test: "",
    locals: {
        test: "",
        test2: false,
        test3: NaN,
        test4: 0,
        test5: undefined,
        auth: {
            user: "hw"
        }
    }
}

keyExistsOn(obj, "")
> false
keyExistsOn(obj, "locals.test")
> true
keyExistsOn(obj, "locals.test2")
> true
keyExistsOn(obj, "locals.test3")
> true
keyExistsOn(obj, "locals.test4")
> true
keyExistsOn(obj, "locals.test5")
> true
keyExistsOn(obj, "sdsdf")
false
keyExistsOn(obj, "sdsdf.rtsd")
false
keyExistsOn(obj, "sdsdf.234d")
false
keyExistsOn(obj, "2134.sdsdf.234d")
false
keyExistsOn(obj, "locals")
true
keyExistsOn(obj, "locals.")
false
keyExistsOn(obj, "locals.auth")
true
keyExistsOn(obj, "locals.autht")
false
keyExistsOn(obj, "locals.auth.")
false
keyExistsOn(obj, "locals.auth.user")
true
keyExistsOn(obj, "locals.auth.userr")
false
keyExistsOn(obj, "locals.auth.user.")
false
keyExistsOn(obj, "locals.auth.user")
true

另请参阅此NPM包:https://www.npmjs.com/package/has-deep-value

其他回答

const object1 = {
  a: 'something',
  b: 'something',
  c: 'something'
};

const key = 's';

// Object.keys(object1) will return array of the object keys ['a', 'b', 'c']

Object.keys(object1).indexOf(key) === -1 ? 'the key is not there' : 'yep the key is exist';

它将返回undefined。

var aa={hello:“world”};警报(aa[“hello”]);//带有“world”的弹出框警报(aa[“再见”]);//带有“未定义”的弹出框

undefined是一个特殊的常量值。所以你可以说,例如。

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

这可能是检查丢失钥匙的最佳方法。然而,正如下面的评论所指出的,理论上,您可能希望未定义实际值。我从来都不需要这样做,也无法马上想到我想要这样做的原因,但为了完整起见,您可以使用in运算符

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

可能只测试与数组键非常不同的对象属性值

在“array”世界中,我们可以将索引视为某种键。令人惊讶的是,in运算符(这是对象的好选择)也适用于数组。不存在键的返回值未定义

设arr=[“a”,“b”,“c”];//我们有索引:0,1,2删除arr[1];//在索引1处设置“空”arr.pop();//删除最后一项console.log(arr中的0,arr[0]);console.log(arr中的1,arr[1]);console.log(arr中的2,arr[2]);

最简单的检查方法是

"key" in object

例如:

var obj = {
  a: 1,
  b: 2,
}
"a" in obj // true
"c" in obj // false

返回值true表示对象中存在键。