本文共 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/