博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何反转JavaScript数组
阅读量:2510 次
发布时间:2019-05-11

本文共 1181 字,大约阅读时间需要 3 分钟。

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()更直观。

翻译自:

转载地址:http://iamgb.baihongyu.com/

你可能感兴趣的文章
[luogu_P2045]方格取数加强版
查看>>
android 代理模式创建Activity
查看>>
c++课程设计之菜单选择\\
查看>>
iOS 的 XMPPFramework 简介
查看>>
hdu 3555 数位dp入门
查看>>
Git学习系列-Git基本概念
查看>>
c#多个程序集使用app.config 的解决办法
查看>>
模仿网站登录注册
查看>>
Linux+Apache+PHP+MySQL服务器环境配置(CentOS篇)
查看>>
Linux下获取本机IP地址的代码
查看>>
(C#)调用Webservice,提示远程服务器返回错误(500)内部服务器错误
查看>>
flex布局
查看>>
python-----python的文件操作
查看>>
字节流例子
查看>>
Chain Of Responsibility Design Pattern Example
查看>>
Windows下curl使用 转载
查看>>
一个简单最大正向匹配(Maximum Matching)MM中文分词算法的实现
查看>>
angularjs中$scope是什么意思?
查看>>
数据校验
查看>>
控制台输出
查看>>