Is there an easy way? Please give me more advice!
天蓬老师2017-05-18 11:02:40
The easiest thing to think of is
` var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;` 或者就是利用字符串和数组的一些方法进行交换,上面也有人提到了。
仅有的幸福2017-05-18 11:02:40
// 给你来个最经典的冒泡排序算法
var arr = [1,3,5,7,9,8,6,4,2];
for (let i = 0; i < arr.length; i++) {
for (let j = i; j < arr.length; j++) {
if (arr[i] < arr[j]) {
// 后面这三行是调换位置的方法
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
console.log(arr);
滿天的星座2017-05-18 11:02:40
Isn’t it easy enough to use tmp
? Then try this
let a=[1,2,3];
[a[1], a[2]]=[a[2], a[1]];
習慣沉默2017-05-18 11:02:40
var a = [1,4,6,43,5,9,0,23,45];
function change(arr,k,j) {
var c = arr[k];
arr[k] = arr[j];
arr[j] = c;
console.log(arr);
}
console.log(a);
change(a,3,7);
PHP中文网2017-05-18 11:02:40
let arr = [1, 2, 3, 4, 5]
// 交换第三个和第四个元素
// x < y
let x = 3, y = 4
arr.splice(x - 1, 1, ...arr.splice(y - 1, 1, arr[x - 1]))
console.log(arr) /// [1,2,4,3,5]