如何在使用序数访问不存在的键时避免错误[重复]
2021-10-01
366
以下代码的结果是 Cat 和 undefined。 *如果键不存在,结果将为“undefined”。
var animals = {"mammals":["Cat","Dog","Cow"]};
var groupA = animals.mammals[0];
var groupB = animals.birds;
console.log(groupA );
console.log(groupB);
但是,以下代码的结果是“error”而不是“undefined”。
*Uncaught TypeError: Cannot read properties of undefined (reading '0')
var animals = {
"mammals": ["Cat", "Dog", "Cow"]
};
var groupA = animals.mammals[0];
var groupB = animals.birds[0];
console.log(groupA);
console.log(groupB);
如果键具有不存在的序数,如何获取“undefined”?
3个回答
您可以使用 可选链接
The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
var animals = {
"mammals": ["Cat", "Dog", "Cow"]
};
var groupA = animals.mammals?.[0];
var groupB = animals.birds?.[0];
console.log(groupA);
console.log(groupB);
Junius L
2021-10-01
您需要先评估属性,见下文:
var animals = {"mammals":["Cat","Dog","Cow"]};
var groupA = animals.mammals[0];
var groupB = (animals.birds || [])[0];
Giusseppe
2021-10-01
您可以检查属性并使用三元组明确设置该值:
var animals = {
"mammals": ["Cat", "Dog", "Cow"]
};
var groupA = animals.mammals ? animals.mammals[0] : undefined;
var groupB = animals.birds ? animals.birds[0] : undefined;
console.log(groupA);
console.log(groupB);
isherwood
2021-10-01