JavaScript 使用一行代码交换两个数组元素
在JavaScript中,有很多方法可以交换两个数组元素。在本文中,我们将讨论一种在JavaScript中使用一行代码交换两个数组元素的方法。输入和输出如下:
Input: arr = { 10, 20, 40, 30 }
Output: arr = { 10, 20, 30, 40 }
// Swapped 30 and 40
方法:使用解构方法
这种方法比任何其他方法都要好。这种方法可以在一行代码中执行。通过将要交换的两个数组元素以及方括号写在左侧,并按照相反的顺序写在右侧,即可完成交换。我们还可以创建一个可重用的函数,用于交换数组的指定索引。
语法:
[a[m], a[n]] = [a[n], a[m]]
// Where m and n are the index numbers to swap
示例1: 在这个示例中,我们将使用JavaScript在一行中交换两个数字数组元素。
let arr = [1, 2, 3, 5, 4];
// Swapping element at index 3 with
// index 4
[arr[3], arr[4]] = [arr[4], arr[3]];
// Print the array
console.log(arr);
输出
[ 1, 2, 3, 4, 5 ]
示例2: 在这个示例中,我们将使用JavaScript在一行中交换两个字符串数组元素。
let arr = ["e", "b", "c", "d", "a"];
// Swapping element at index 0 with
// index 4
[arr[0], arr[4]] = [arr[4], arr[0]];
// Print the array
console.log(arr);
输出
[ 'a', 'b', 'c', 'd', 'e' ]
极客教程