如何处理JavaScript中的未定义键

如何处理JavaScript中的未定义键

在本文中,我们将尝试分析如何使用某些技巧或方法(通过一些编码示例)来处理JavaScript中的未定义键(或对象的属性)。

首先,让我们快速分析如何使用以下语法创建带有特定键及其值的对象:

语法:

let object_name = {
    property_name : value,
    ...
}
HTML

现在让我们看下面的示例,它将帮助我们理解对象创建语法:

示例: 在此示例中,我们将简单地创建一个具有特定属性和特定值的对象。

<script>
    let employee_details = {
      firstName: "ABC",
      lastName: "DEF",
      age: 22,
      designation: "Technical Content Writer",
      organizationName: "GeeksforGeeks",
    };

    console.log(employee_details);
    console.log(
      `Complete name of an employee is 
          {employee_details.firstName}{employee_details.lastName}`
    );
</script>
HTML

输出:

{
  firstName: 'ABC',
  lastName: 'DEF',
  age: 22,
  designation: 'Technical Content Writer',
  organizationName: 'GeeksforGeeks'
}
Complete name of an employee is ABC DEF
HTML

现在我们已经了解了对象创建过程,让我们看一些以下通过这些方法/条件/案例来解决问题陈述(处理未定义键):

方法1: 在这种方法中,我们将使用前面示例中创建的相同对象,并进一步尝试访问一个在该对象中未定义的键,同时还会处理错误。

示例1:

<script>
    let employee_details = {
        firstName: "ABC",
        lastName: "DEF",
        age: 22,
        designation: "Technical Content Writer",
        organizationName: "GeeksforGeeks",
    };

    console.log(
        `Address of an employee is : 
            ${employee_details?.address ?? "not found"}`
    );
</script>
HTML

输出:

Address of an employee is : not found
HTML

示例2:

<script>
    let employee_details = {
        firstName: "ABC",
        lastName: "DEF",
        age: 22,
        designation: "Technical Content Writer",
        organizationName: "GeeksforGeeks",
    };

    console.log(
        `Address of an employee is : 
          ${"address" in employee_details ? 
          employee_details.address : 
          "not found"
        }`
    );
</script>
HTML

输出:

Address of an employee is : not found
HTML

方法2: 在这种方法中,我们将使用相同的对象,但在这里,我们将显式地添加一个键(或属性),其值为“undefined”,然后在访问时查看输出。

示例:

<script>
    let employee_details = {
      firstName: "ABC",
      lastName: "DEF",
      age: 22,
      designation: "Technical Content Writer",
      organizationName: "GeeksforGeeks",
      address: undefined,
    };
  
    console.log(
      `员工的地址是: ${
        employee_details?.address === undefined
          ? "未定义"
          : employee_details.address
      }`
    );
</script>
HTML

输出:

员工的地址是:未定义
HTML

阅读更多:JavaScript 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册