array .prototype.reverse将数组的内容反向(带有突变)…
是否有类似的简单策略来反转数组而不改变原始数组的内容(不发生突变)?
array .prototype.reverse将数组的内容反向(带有突变)…
是否有类似的简单策略来反转数组而不改变原始数组的内容(不发生突变)?
当前回答
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 () 箭头功能 逗号操作符
其他回答
你可以使用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);
试试这个递归解决方案:
const reverse = ([head, ...tail]) =>
tail.length === 0
? [head] // Base case -- cannot reverse a single element.
: [...reverse(tail), head] // Recursive case
reverse([1]); // [1]
reverse([1,2,3]); // [3,2,1]
reverse('hello').join(''); // 'olleh' -- Strings too!
仅出于演示目的,使用变量交换进行反向(但如果不想发生变化,则需要一个副本)
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]]
}
在ES6:
const newArray = [...array].reverse()
使用.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]), []);