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

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


当前回答

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的其他用法

其他回答

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';

JS双感叹号!!在这种情况下,符号可能会有所帮助。

const cars = {
        petrol:{
            price: 5000
        },
        gas:{
            price:8000
        }
    }

假设我们有上面的对象,如果你试图用汽油价格记录汽车。

=> console.log(cars.petrol.price);
=> 5000

你肯定会从中得到5000英镑。但如果你想得到不存在的电动汽车,那么你将不受约束

=> console.log(cars.electric);
=> undefine

但使用!!这是将变量转换为布尔值(真或假)。

=> console.log(!!cars.electric);
=> false

在“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表示对象中存在键。

const rawObject = {};
rawObject.propertyKey = 'somethingValue';

console.log(rawObject.hasOwnProperty('somethingValue'));
// expected output: true

检查给定对象中存在的特定键,hasOwnProperty将在此处工作。