1.引入第三个变量
var arr = ['one','two']; var item = arr[0]; arr[0] = arr[1]; arr[1] = item;
2.splice方法, splice() 方法会直接对数组进行修改,splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。
arr.splice(1,1,arr[0]) 将第二个值替换成第一个值,...arr.splice(1,1,arr[0])拿到被替换的值,即第二个值,
arr.splice(0,1,...arr.splice(1,1,arr[0]))将第一个值换成第二个值
var arr = ['one','two']; arr.splice(0,1,...arr.splice(1,1,arr[0])) // 或者 arr.splice(0,1,arr.splice(1,1,arr[0])[0]) //arr.splice(index2,1,...arr.splice(index1, 1 , arr[index2]));
3.数组解构赋值
var arr = ['one','two']; [arr[0],arr[1]] = [arr[1],arr[0]] // [arr[index1],arr[index2]] = [arr[index2],arr[index1]];