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

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


当前回答

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

其他回答

es6:

const reverseArr = [1,2,3,4].sort(()=>1)
const arrayCopy = Object.assign([], array).reverse()

这个解决方案:

-成功复制array

-不会改变原始数组

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

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

是的,有一种方法可以通过使用to[Operation]来实现这一点,它返回一个带有应用操作的新集合(目前处于第3阶段,很快就会可用)。

实现方式如下:

const arr = [5, 4, 3, 2, 1];

const reversedArr = arr.toReverse();

console.log(arr); // [5, 4, 3, 2, 1]

console.log(reversedArr); // [1, 2, 3, 4, 5]

虽然不是最好的解决方案,但确实有效 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);

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