第一种方式 :
function changeLoc(array,from,to){
if((from > array.length-1 || from < 0) || (to > array.length-1 || to < 0)){
console.error("指定位置错误");
return;
}
[array[from],array[to]] = [array[to],array[from]]
return array
}
arr = [1,2,3,4]
(4) [1, 2, 3, 4]
changeLoc(arr,1,3)
(4) [1, 4, 3, 2]
第二种方式 :
function move(array, before, to) {
if((before > array.length-1 || before < 0) || (to > array.length-1 || to < 0)) {
console.error("指定位置错误");
return;
}
const newArray = [...array];
const elem = newArray.splice(before, 1);
const newarr = newArray.splice(to, 0, ...elem);
return newArray;
}
const array = [1, 2, 3, 4];
console.log(move(array, 0, 3));