【发布时间】:2023-03-18 20:38:01
【问题描述】:
我正在努力解决这个问题。在下面的小提琴中,我如何解释 itemChild 可能不存在的情况? 当我删除它时,我收到以下错误 (index):49 Uncaught TypeError: Cannot read property 'cat' of undefined
const item = {
name: "firstItem",
color: "red",
shape: "square",
size: "big",
itemChild: {
cat: "category1",
age: "10"
}
}
let {
name,
color,
shape,
size,
itemChild = {},
itemChild: {
cat = "",
age = ""
}
} = item;
if (itemChild) {
console.log("Child", cat, age);
} else {
console.log("Parent", name, color);
}
【问题讨论】:
-
您需要将嵌套的目标赋值和默认值加入到同一个属性元素中:
itemChild: { cat = "", age = "" } = {}。您的两个itemChild目标是分开的。 -
嘿,谢谢,为什么默认赋值不在元素本身上?...所以当 itemChild 未定义时,它会变成 {} ?
-
这只是语法:
propertyName: assignmentTarget = defaultValue。它正是这样做的。
标签: javascript