如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
当前回答
接受的答案指的是对象。小心使用Array上的in运算符查找数据而不是键:
("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)
测试数组中的现有元素:查找项目是否在JavaScript数组中的最佳方法?
其他回答
如果在项目中配置了ESLint,则遵循ESLint规则,没有内置原型。以下链接描述了原因:
// bad
console.log(object.hasOwnProperty(key));
// good
console.log(Object.prototype.hasOwnProperty.call(object, key));
// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
console.log(has.call(object, key));
/* or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));
"key" in obj
可能只测试与数组键非常不同的对象属性值
const rawObject = {};
rawObject.propertyKey = 'somethingValue';
console.log(rawObject.hasOwnProperty('somethingValue'));
// expected output: true
检查给定对象中存在的特定键,hasOwnProperty将在此处工作。
ES6溶液
使用Array#some和Object.keys。如果给定的键存在于对象中,则返回true,否则返回false。
var obj={foo:'one',bar:'two'};函数isKeyInObject(obj,key){var res=对象.keys(obj).some(v=>v==key);console.log(res);}isKeyInObject(obj,'foo');isKeyInObject(obj,“something”);
单行示例。
console.log(Object.keys({foo:'one',bar:'two'}).some(v=>v=='foo'));
要查找对象中是否存在键,请使用
对象.keys(obj).includes(key)
ES7包括检查数组是否包含项的方法,这是indexOf的一种更简单的替代方法。