示例1:使用操作符检查对象中是否存在键
// program to check if a key exists
let person = {
id: 1,
name: 'John',
age: 23
}
// check if key exists
let 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
let person = {
id: 1,
name: 'John',
age: 23
}
//check if key exists
let 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
。