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
167 views
in Technique[技术] by (71.8m points)

javascript - Javascript交换数组元素(Javascript swap array elements)

Is there any simpler way to swap two elements in an array?(有没有更简单的方法来交换数组中的两个元素?)

var a = list[x], b = list[y]; list[y] = a; list[x] = b;   ask by ken translate from so

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

1 Reply

0 votes
by (71.8m points)

You only need one temporary variable.(您只需要一个临时变量。)

var b = list[y]; list[y] = list[x]; list[x] = b; Edit hijacking top answer 10 years later with a lot of ES6 adoption under our belts:(10年后,我们大量采用了ES6,从而编辑劫持性最高答案:) Given the array arr = [1,2,3,4] , you can swap values in one line now like so:(给定数组arr = [1,2,3,4] ,您现在可以像这样在一行中交换值:) [arr[0], arr[1]] = [arr[1], arr[0]]; This would produce the array [2,1,3,4] .(这将产生数组[2,1,3,4] 。) This is destructuring assignment .(这是破坏性的任务 。)

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

...