简体   繁体   中英

Destructuring assignment and variable swapping

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?

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM