Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
303 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...