JavaScript 程序:检查对象中是否存在某个键

要理解此示例,您应了解以下 JavaScript 编程 主题


示例 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


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战