array .prototype.reverse将数组的内容反向(带有突变)…

是否有类似的简单策略来反转数组而不改变原始数组的内容(不发生突变)?


当前回答

const originalArray = [a, b, c, d, e, f); const newArray = Array.from(originalArray).reverse(); console.log (newArray);

其他回答

有多种方法可以在不修改的情况下反转数组。其中两个是

var array = [1,2,3,4,5,6,7,8,9,10];

// Using Splice
var reverseArray1 = array.splice().reverse(); // Fastest

// Using spread operator
var reverseArray2 = [...array].reverse();

// Using for loop 
var reverseArray3 = []; 
for(var i = array.length-1; i>=0; i--) {
  reverseArray.push(array[i]);
}

性能测试http://jsben.ch/guftu

使用.reduce()和spread的ES6替代方案。

const foo = [1, 2, 3, 4];
const bar = foo.reduce((acc, b) => ([b, ...acc]), []);

基本上,它所做的是用foo中的下一个元素创建一个新数组,并在b之后的每次迭代中扩展累积的数组。

[]
[1] => [1]
[2, ...[1]] => [2, 1]
[3, ...[2, 1]] => [3, 2, 1]
[4, ...[3, 2, 1]] => [4, 3, 2, 1]

或者如上所述的. reduceright(),但没有.push()突变。

const baz = foo.reduceRight((acc, b) => ([...acc, b]), []);

仅出于演示目的,使用变量交换进行反向(但如果不想发生变化,则需要一个副本)

const myArr = ["a", "b", "c", "d"];
const copy = [...myArr];
for (let i = 0; i < (copy.length - 1) / 2; i++) {  
    const lastIndex = copy.length - 1 - i; 
    [copy[i], copy[lastIndex]] = [copy[lastIndex], copy[i]] 
}

const arrayCopy = Object.assign([], array).reverse()

这个解决方案:

-成功复制array

-不会改变原始数组

-看起来它在做它该做的事

虽然不是最好的解决方案,但确实有效 Array.prototype.myNonMutableReverse = function () { const reversedArr = []; 对于(let I = this。)长度- 1;I >= 0;我——)reversedArr.push(这[我]); 返回reversedArr; }; Const a = [1,2,3,4,5,6,7,8]; const b = a.myNonMutableReverse(); console.log(“a”); console.log ("////////") console.log (b, b);