Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

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

用于检查对象中是否存在键的 JavaScript 程序

在本例中,您将学习编写一个 JavaScript 程序来检查对象中是否存在键。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 对象 JavaScript 对象 hasOwnProperty()

示例 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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4