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

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


当前回答

香草js

yourObjName.hasOwnProperty(key) : true ? false;

如果要检查对象在es2015中是否至少有一个属性

Object.keys(yourObjName).length : true ? false

其他回答

检查javascript对象中是否存在属性的三种方法:

!!对象.属性将值转换为布尔值。对于除false值之外的所有值返回true对象中的“属性”如果属性存在,无论其值如何(甚至为空),都将返回trueobj.hasOwnProperty(“属性”)不检查原型链。(由于所有对象都有toString方法,因此1和2将返回true,而3可以返回false。)

参考:

http://book.mixu.net/node/ch5.html

JavaScript Destructuring的新解决方案:

let obj = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
};

let {key1, key2, key3, key4} = obj;

// key1 = "value1"
// key2 = "value2"
// key3 = "value3"
// key4 = undefined

// Can easily use `if` here on key4
if(!key4) { console.log("key not present"); } // Key not present

检查JavaScript Destructuring的其他用法

yourArray.indexOf(yourArrayKeyName)>-1

fruit = ['apple', 'grapes', 'banana']

fruit.indexOf('apple') > -1

true


fruit = ['apple', 'grapes', 'banana']

fruit.indexOf('apple1') > -1

假的


对于严格的对象键检查:

const object1 = {};
object1.stackoverflow = 51; 
console.log(object1.hasOwnProperty('stackoverflow')); 



output: true 

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

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

接受的答案指的是对象。小心使用Array上的in运算符查找数据而不是键:

("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)

测试数组中的现有元素:查找项目是否在JavaScript数组中的最佳方法?