博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何在JavaScript中交换两个数组元素
阅读量:2507 次
发布时间:2019-05-11

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

How do you swap 2 elements in an array, in JavaScript?

如何在JavaScript中交换数组中的2个元素?

Suppose we have an array a which contains 5 letters.

假设我们有一个包含5个字母的数组a

const a = ['a', 'b', 'c', 'e', 'd']

We want to swap element at index 4 (’d’ in this case) with the element at index 3 (‘e’ in this case).

我们希望将索引4的元素(在这种情况下为'd')与索引3的元素(在这种情况下为'e')交换。

We can use a temporary item tmp to store the value of #4, then we put #3 in place of #4, and we assign the temporary item to #3:

我们可以使用临时项目tmp存储#4的值,然后将#3替换为#4,然后将临时项目分配给#3:

const tmp = a[4]a[4] = a[3]a[3] = tmp

Another option, which does not involve declaring a temporary variable, is to use this syntax:

不涉及声明临时变量的另一个选项是使用以下语法:

const a = ['a', 'b', 'c', 'e', 'd'];[a[3], a[4]] = [a[4], a[3]]

Now the array a will be correctly ordered as we want.

现在,数组a将根据需要正确排序。

a //[ 'a', 'b', 'c', 'd', 'e' ]

翻译自:

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

你可能感兴趣的文章
npm 安装 sass=-=-=
查看>>
WINFORM中加入WPF控件并绑定数据源实现跨线程自动更新
查看>>
C#类对象的事件定义
查看>>
各类程序员学习路线图
查看>>
HDU 5510 Bazinga KMP
查看>>
关于select @@IDENTITY的初识
查看>>
ASP.NET MVC ajax提交 防止CSRF攻击
查看>>
关于CSS伪类选择器
查看>>
适用于带文字 和图片的垂直居中方法
查看>>
Part 2 - Fundamentals(4-10)
查看>>
使用Postmark测试后端存储性能
查看>>
NSTextView 文字链接的定制化
查看>>
第五天站立会议内容
查看>>
CentOs7安装rabbitmq
查看>>
(转))iOS App上架AppStore 会遇到的坑
查看>>
解决vmware与主机无法连通的问题
查看>>
做好产品
查看>>
项目管理经验
查看>>
笔记:Hadoop权威指南 第8章 MapReduce 的特性
查看>>
JMeter响应数据出现乱码的处理-三种解决方式
查看>>