JavaScript 如何处理未定义的键
在本文中,我们尝试通过一些编码示例来分析如何使用特定的技术或方法来处理JavaScript中的未定义键(或对象的属性)。
首先,让我们快速分析如何使用以下语法创建具有特定键及其值的对象:
语法:
let object_name = {
property_name : value,
...
}
现在让我们来看下面的示例,它将帮助我们理解对象创建的语法:
示例: 在这个示例中,我们将简单地创建一个具有特定属性和特定值的对象。
Javascript
<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>
输出:
{
firstName: 'ABC',
lastName: 'DEF',
age: 22,
designation: 'Technical Content Writer',
organizationName: 'GeeksforGeeks'
}
Complete name of an employee is ABC DEF
现在,我们已经理解了对象的创建过程,让我们通过以下一些示例方法/ 条件/ 情况来更好地理解问题陈述(即处理未定义键的方法):
方法1: 在这种方法中,我们将使用在先前示例中创建的相同对象,并尝试访问一个在该对象中未定义的键,并处理错误。
示例1:
Javascript
<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>
输出:
Address of an employee is : not found
示例2:
JavaScript
<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>
输出:
Address of an employee is : not found
第二种方法: 在这种方法中,我们将使用相同的对象,但是在这里我们将显式地添加一个额外的键(或属性),值为“undefined”,然后在访问时观察输出。
示例:
Javascript
<script>
let employee_details = {
firstName: "ABC",
lastName: "DEF",
age: 22,
designation: "Technical Content Writer",
organizationName: "GeeksforGeeks",
address: undefined,
};
console.log(
`Address of an employee is : ${
employee_details?.address === undefined
? "not defined"
: employee_details.address
}`
);
</script>
输出:
Address of an employee is : not defined
极客教程