问题
I am trying to do array destructuring in javascript and encounter some very puzzling behavior
Here's the code I have --
let res = {
start: {},
end: {},
};
[res.start.hour, res.start.minute] = [7, 20]
[res.end.hour, res.end.minute] = [17, 30]
console.log(res)
The output is
{ start: { hour: 17, minute: 30 }, end: {} }
For some reason, [17, 30] were assigned to res.start, instead of res.end.
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)
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 } }
I've searched, and read thru MDN page on destructure, but couldn't find an explanation to this. Appreciate your help in advance.
回答1:
Try this:
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);
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);
As it turns out, semicolons do matter sometimes in JavaScript.
来源:https://stackoverflow.com/questions/55347263/destructuring-array-into-an-object