跳到主要内容

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

要理解这个示例,你应该具备以下 JavaScript 编程 主题的知识:

示例 1:使用 in 操作符检查对象中是否存在键

// 程序用来检查对象中是否存在某个键

const person = {
id: 1,
name: "John",
age: 23,
};

// 检查键是否存在
const hasKey = "name" in person;

if (hasKey) {
console.log("该键存在。");
} else {
console.log("该键不存在。");
}

输出

该键存在。

在上述程序中,使用 in 操作符来检查对象中是否存在某个键。in 操作符会返回 true,如果指定的键存在于对象中,否则返回 false

示例 2:使用 hasOwnProperty() 方法检查对象中是否存在键

// 程序用来检查对象中是否存在某个键

const person = {
id: 1,
name: "John",
age: 23,
};

// 检查键是否存在
const hasKey = person.hasOwnProperty("name");

if (hasKey) {
console.log("该键存在。");
} else {
console.log("该键不存在。");
}

输出

该键存在。

在上述程序中,使用 hasOwnProperty() 方法来检查对象中是否存在某个键。hasOwnProperty() 方法会返回 true,如果指定的键存在于对象中,否则返回 false