array .prototype.reverse将数组的内容反向(带有突变)…
是否有类似的简单策略来反转数组而不改变原始数组的内容(不发生突变)?
array .prototype.reverse将数组的内容反向(带有突变)…
是否有类似的简单策略来反转数组而不改变原始数组的内容(不发生突变)?
当前回答
const arrayCopy = Object.assign([], array).reverse()
这个解决方案:
-成功复制array
-不会改变原始数组
-看起来它在做它该做的事
其他回答
es6:
const reverseArr = [1,2,3,4].sort(()=>1)
虽然不是最好的解决方案,但确实有效 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);
ES6的另一个变体:
我们也可以使用. reduceright()来创建一个反向数组,而不是真正地将它反向。
let A = [' A ', 'b', 'c', 'd', 'e', 'f']; 让B = A.reduceRight ((a、c) = > (a.push (c), a), []); console.log (B);
有用的资源:
Array.prototype.reduceRight () 箭头功能 逗号操作符
仅出于演示目的,使用变量交换进行反向(但如果不想发生变化,则需要一个副本)
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]]
}
你可以使用slice()来复制,然后reverse()它
var newarray = array.slice().reverse();
Var array = ['a', 'b', 'c', 'd', 'e']; Var newarray = array.slice().reverse(); console.log (a、数组); console.log(“na”,newarray);