📝 JavaScript 检查对象中是否存在指定 key
2025-01-22 08:19:30    285 字   
This post is also available in English and alternative languages.

三种方式,检查对象中是否存在指定的key。


1. in 运算符

in 运算符可以检查对象中是否存在属性。

1
2
3
4
5
6
7
8
9
10
11
var person = {
name: 'John',
age: 30,
city: 'New York'
};

if ('name' in person) {
console.log('The property "name" exists in the person object.');
} else {
console.log('The property "name" does not exist in the person object.');
}

2. hasOwnProperty 方法

hasOwnProperty 方法检查对象是否直接包含属性。

1
2
3
4
5
6
7
8
9
10
11
var person = {
name: 'John',
age: 30,
city: 'New York'
}

if (person.hasOwnProperty('name')) {
console.log('The property "name" exists in the person object.');
} else {
console.log('The property "name" does not exist in the person object.');
}

3. 使用 !== undefined 比较

1
2
3
4
5
6
7
8
9
10
11
var person = {
name: 'John',
age: 30,
city: 'New York'
};

if (person['name'] !== undefined) {
console.log('The property "name" exists in the person object.');
} else {
console.log('The property "name" does not exist in the person object.');
}

4. FAQ

  • 使用 inhasOwnProperty 检查键的区别是什么?

    in 运算符检查属性是否存在于对象的原型链中,而 hasOwnProperty 检查属性是否直接存在于对象本身。