I had the need to reverse a JavaScript array, and here is what I did.
我需要反转JavaScript数组,这就是我所做的。
Given an array list
:
给定一个数组list
:
const list = [1, 2, 3, 4, 5]
The easiest and most intuitive way is to call the reverse()
method of an array.
最简单,最直观的方法是调用数组的reverse()
方法。
This method alters the original array, so I can declare list
as a const, because I don’t need to reassign the result of calling list.reverse()
to it:
此方法会更改原始数组,因此我可以将list
声明为const,因为我不需要将调用list.reverse()
的结果重新分配给它:
const list = [1, 2, 3, 4, 5]
list.reverse()
//list is [ 5, 4, 3, 2, 1 ]
You can pair this method with the spread operator to first copy the original array, and then reversing it, so the original array is left untouched:
您可以将此方法与散布运算符配对使用,以首先复制原始数组,然后将其反转,因此原始数组将保持不变:
const list = [1, 2, 3, 4, 5]
const reversedList = [...list].reverse()
//list is [ 1, 2, 3, 4, 5 ]
//reversedList is [ 5, 4, 3, 2, 1 ]
Another way is to use slice()
without passing arguments:
另一种方法是使用slice()
而不传递参数:
const list = [1, 2, 3, 4, 5]
const reversedList = list.slice().reverse()
//list is [ 1, 2, 3, 4, 5 ]
//reversedList is [ 5, 4, 3, 2, 1 ]
but I find the spread operator more intuitive than slice()
.
但是我发现散布运算符比slice()
更直观。
翻译自: https://flaviocopes.com/how-to-reverse-array-javascript/