This question already has an answer here:
这个问题在这里已有答案:
- Javascript fastest way to duplicate an Array - slice vs for loop 15 answers
- Javascript最快的复制数组的方法 - 切片vs for循环15的答案
I'm trying to reverse the order of an array using the .reverse() method in JavaScript, but also trying to preserve the original order of elements in the original array. When I save the values into a variable, I end up transposing the elements in the original array as well as creating a new one with the same format. What is the most eloquent way to perform this task?
我试图在JavaScript中使用.reverse()方法来反转数组的顺序,但也试图保留原始数组中元素的原始顺序。当我将值保存到变量中时,我最终转换原始数组中的元素以及创建具有相同格式的新元素。执行此任务最有说服力的方法是什么?
var arrayOne = [1,2,3,4,5];
var arrayTwo = arrayOne.reverse();
//arrayTwo = [5, 4, 3, 2, 1]
//arrayOne = [5, 4, 3, 2, 1]
1 个解决方案
#1
7
var arrayTwo = arrayOne.slice().reverse();
Slice will clone the array
Slice将克隆数组
#1
7
var arrayTwo = arrayOne.slice().reverse();
Slice will clone the array
Slice将克隆数组