示例 1: 检查 Key 在 Object Using in Operator 中是否存在
// 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
。