如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
当前回答
接受的答案指的是对象。小心使用Array上的in运算符查找数据而不是键:
("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)
测试数组中的现有元素:查找项目是否在JavaScript数组中的最佳方法?
其他回答
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的其他用法
值得注意的是,自从引入ES11以来,您可以使用零合并运算符,这大大简化了事情:
const obj = {foo: 'one', bar: 'two'};
const result = obj.foo ?? "Not found";
上面的代码将为foo中的任何“falsy”值返回“Not found”。否则将返回obj.foo。
请参见与零合并运算符组合
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
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';
如果您使用的是underscore.js库,那么对象/数组操作就变得简单了。
在您的情况下,可以使用_.has方法。例子:
yourArray = {age: "10"}
_.has(yourArray, "age")
返回true
But,
_.has(yourArray, "invalidKey")
返回false