Destructuring assignment and variable swapping

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-05 06:32:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!