Array.prototype.reverse
原地反转数组的内容(带有突变)...
是否有类似的简单策略来反转数组而不改变原始数组的内容(没有突变)?
Array.prototype.reverse
原地反转数组的内容(带有突变)...
是否有类似的简单策略来反转数组而不改变原始数组的内容(没有突变)?
在 ES6 中:
const newArray = [...array].reverse()
另一个 ES6 变体:
我们还可以使用.reduceRight()
来创建一个反转数组,而无需实际反转它。
let A = ['a', 'b', 'c', 'd', 'e', 'f'];
let B = A.reduceRight((a, c) => (a.push(c), a), []);
console.log(B);
有用的资源:
试试这个递归解决方案:
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!
ES6 的替代使用.reduce()
和传播。
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]), []);