Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

javascript - How does [b][b = a,0] swap between a and b?

As gdoron pointed out,

var a = "a";
var b = "b";

a = [b][b = a,0];

Will swap a and b, and although it looks a bit of hacky, it has triggered my curiosity and I am very curious at how it works. It doesn't make any sense to me.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
var a = "a";
var b = "b";

a = [b][b = a, 0];

Let's break the last line into pieces:

[b]       // Puts b in an array - a safe place for the swap.
[b = a]   // Assign a in b
[b = a,0] // Assign a in b and return the later expression - 0 with the comma operator.

so finally it is a =[b][0] - the first object in the [b] array => b assigned to a

Live DEMO

read @am not I am comments in this question:
When is the comma operator useful?
It's his code...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...