问题
Javascript allows swapping of variables:
var x = 1
var y = 2
[x, y] = [y, x] // y = 1 , x = 2
And destructured assignment:
var a, b
[a, b] = [1, 2]
log(a) // 1
log(b) // 2
When using variable swapping in lieu with destructured assignment, trying to swap variables breaks down:
var a, b
[a, b] = [1, 2] // a = 1, b = 2
[a, b] = [b, a] // TypeError: Cannot set property '2' of undefined
Why is that?
回答1:
If you decide to omit semicolons (no judgement, I prefer it that way too), don't forget to prefix lines beginning with array literals with ;
. Occasionally, semicolon insertion does matter, because it might not occur when you want or expect it to.
var a, b
;[a, b] = [1, 2]
;[a, b] = [b, a]
console.log(a, b)
来源:https://stackoverflow.com/questions/42562806/destructuring-assignment-and-variable-swapping