如何反转JavaScript数组

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/

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值