示例 1:使用 in 运算符检查对象中是否存在键
// program to check if a key exists
const person = {
id: 1,
name: 'John',
age: 23
}
// check if key exists
const hasKey = 'name' in person;
if(hasKey) {
console.log('The key exists.');
}
else {
console.log('The key does not exist.');
}
输出
The key exists.
在上面的程序中,使用 in 运算符来检查对象中是否存在某个键。如果指定的键存在于对象中,则 in
运算符返回 true
,否则返回 false
。
示例 2:使用 hasOwnProperty() 检查对象中是否存在键
// program to check if a key exists
const person = {
id: 1,
name: 'John',
age: 23
}
//check if key exists
const hasKey = person.hasOwnProperty('name');
if(hasKey) {
console.log('The key exists.');
}
else {
console.log('The key does not exist.');
}
输出
The key exists.
在上面的程序中,使用 hasOwnProperty()
方法来检查对象中是否存在某个键。如果指定的键存在于对象中,则 hasOwnProperty()
方法返回 true
,否则返回 false
。
另请阅读