在 Javascript 中反转数组而不改变原始数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30610523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:27:23  来源:igfitidea点击:

Reverse array in Javascript without mutating original array

javascriptarrays

提问by sfletche

Array.prototype.reversereverses the contents of an array in place (with mutation)...

Array.prototype.reverse原地反转数组的内容(带有突变)...

Is there a similarly simple strategy for reversing an array without altering the contents of the original array (without mutation)?

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

回答by Arun P Johny

You can use slice()to make a copy then reverse()it

您可以使用片() ,使该拷贝逆转()

var newarray = array.slice().reverse();

var array = ['a', 'b', 'c', 'd', 'e'];
var newarray = array.slice().reverse();

console.log('a', array);
console.log('na', newarray);

回答by Brian M. Hunt

In ES6:

在 ES6 中:

const newArray = [...array].reverse()

回答by Mohammad Usman

Another ES6 variant:

另一个 ES6 变体:

We can also use .reduceRight()to create a reversed array without actually reversing it.

我们还可以使用.reduceRight()来创建一个反转数组,而无需实际反转它。

let A = ['a', 'b', 'c', 'd', 'e', 'f'];

let B = A.reduceRight((a, c) => (a.push(c), a), []);

console.log(B);

Useful Resources:

有用的资源:

回答by Austin Keeton

Try this recursive solution:

试试这个递归解决方案:

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!                              

回答by hanswilw

An ES6 alternative using .reduce()and spreading.

ES6 的替代使用.reduce()和传播。

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

Basically what it does is create a new array with the next element in foo, and spreading the accumulated array for each iteration after b.

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

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

Alternatively .reduceRight()as mentioned above here, but without the .push()mutation.

或者.reduceRight()如上所述这里,但没有.push()突变。

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

回答by shekhardtu

There are multiple ways of reversing an array without modifying. Two of them are

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

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]);
}

Performance test http://jsben.ch/guftu

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

回答by Amit kumar

INTO plain Javascript:

INTO纯Javascript:

function reverseArray(arr, num) {
  var newArray = [];
  for (let i = num; i <= arr.length - 1; i++) {
    newArray.push(arr[i]);
  }

  return newArray;
}

回答by daino3

Reversing in place with variable swap just for demonstrative purposes (but you need a copy if you don't want to mutate)

仅出于演示目的使用变量交换就地反转(但如果您不想变异,则需要一个副本)

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]] 
}

回答by Radion Ponomarenko

es6:

es6:

const reverseArr = [1,2,3,4].sort(()=>1)