解构包含对象的数组
destructing array containing objects
let chosen = 4;
let team = [
{ titel: "ahmad", age: 20, available: true, skills: ["html", "css"] },
{ titel: "mizo", age: 30, available: false, skills: ["js", "react"] },
{ titel: "jo", age: 40, available: true, skills: ["pyhton", "django"] },
];
(() => {
if (chosen === chosen) {
let {
titel,
age,
available,
skills: [s1, s2],
} = team[chosen - 1];
console.log(`Team-${chosen}:
name: ${titel}
age: ${age}
skill: ${s1}
availability: ${(() => {
if (available) return `available`;
else return `unavailable`;
})()}
`);
} else return;
})();
为什么上面给定的代码会抛出这个错误
(Uncaught TypeError: Cannot destructure 属性 'titel' of 'team[(chosen - 1)]' as it is undefined.) 在控制台中如果你选择一个小于 1 或大于 4 的数字 ??
这是因为超出了数组的元素个数。
团队数组有 3 个项目。
要访问索引为 0 的第一项,您可以执行 team[0]。
要访问索引为 2 的最后一项,您需要执行团队 [2]
当您执行 team[4-1] 时,您最终得到的 team[3] 超出了数组的长度,因此未定义。
请记住,javascript 中的数组是从 0 开始索引的。这意味着第一项始终位于索引 0,最后一项位于 team.length-1,在本例中为 2.
let chosen = 4;
let team = [
{ titel: "ahmad", age: 20, available: true, skills: ["html", "css"] },
{ titel: "mizo", age: 30, available: false, skills: ["js", "react"] },
{ titel: "jo", age: 40, available: true, skills: ["pyhton", "django"] },
];
(() => {
if (chosen === chosen) {
let {
titel,
age,
available,
skills: [s1, s2],
} = team[chosen - 1];
console.log(`Team-${chosen}:
name: ${titel}
age: ${age}
skill: ${s1}
availability: ${(() => {
if (available) return `available`;
else return `unavailable`;
})()}
`);
} else return;
})();
为什么上面给定的代码会抛出这个错误 (Uncaught TypeError: Cannot destructure 属性 'titel' of 'team[(chosen - 1)]' as it is undefined.) 在控制台中如果你选择一个小于 1 或大于 4 的数字 ??
这是因为超出了数组的元素个数。
团队数组有 3 个项目。
要访问索引为 0 的第一项,您可以执行 team[0]。
要访问索引为 2 的最后一项,您需要执行团队 [2]
当您执行 team[4-1] 时,您最终得到的 team[3] 超出了数组的长度,因此未定义。
请记住,javascript 中的数组是从 0 开始索引的。这意味着第一项始终位于索引 0,最后一项位于 team.length-1,在本例中为 2.