将数组分解为对象 [英] Destructuring array into an object
问题描述
我正在尝试用javascript进行数组解构并遇到一些令人费解的行为
I am trying to do array destructuring in javascript and encounter some very puzzling behavior
这是我的代码-
let res = {
start: {},
end: {},
};
[res.start.hour, res.start.minute] = [7, 20]
[res.end.hour, res.end.minute] = [17, 30]
console.log(res)
输出为
{ start: { hour: 17, minute: 30 }, end: {} }
由于某种原因,[17,30]被分配给res.start,而不是res.end.
For some reason, [17, 30] were assigned to res.start, instead of res.end.
此外,如果我添加如下的console.log语句
Furthermore, if I add a console.log statement like below
let res = {
start: {},
end: {},
};
[res.start.hour, res.start.minute] = [7, 20]
console.log(JSON.stringify(res));
[res.end.hour, res.end.minute] = [17, 30]
console.log(res)
然后它起作用.res.end将获得正确的值.输出-
Then it works. res.end would get the correct value. Output --
{"start":{"hour":7,"minute":20},"end":{}}
{ start: { hour: 7, minute: 20 },
end: { hour: 17, minute: 30 } }
我进行了搜索,并阅读了有关MDN的MDN页面,但找不到对此的解释.提前感谢您的帮助.
I've searched, and read thru MDN page on destructure, but couldn't find an explanation to this. Appreciate your help in advance.
推荐答案
尝试一下:
let res = {
start: {},
end: {}
};
[res.start.hour, res.start.minute] = [7, 20]; // Notice the semicolons.
[res.end.hour, res.end.minute] = [17, 30];
console.log(res);
我将您的代码从第一块复制粘贴到VS Code中,并使用了"Alt + Shift + F"(自动格式化).它将代码固定为以下代码,表明明显有问题:
I copy-pasted your code from the first block into VS Code and used 'Alt + Shift + F' (auto-formatting). It fixed the code to the following, indicating that something is clearly off:
let res = {
start: {},
end: {}
};
[res.start.hour, res.start.minute] = [7, 20][(res.end.hour, res.end.minute)] = [
17,
30
];
console.log(res);
事实证明,分号有时在JavaScript中确实很重要.
As it turns out, semicolons do matter sometimes in JavaScript.
这篇关于将数组分解为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!