写一个数组内移动元素的函数
2020-03-16 本文已影响0人
小雪洁
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数组移动元素</title>
</head>
<body>
<script>
//只能移动单个元素,实现某两个元素的交换
function move(array,from,to){
if(from<0||to>array.length){
console.error("参数错误!");
}
const newArray =[...array];
let item =newArray[to];
newArray[to]=newArray[from];
newArray[from]=item;
return newArray;
}
let a=[1,2,3,4,5];
console.log(move(a,0,6));
//参数错误! [undefined, 2, 3, 4, 5, empty, 1]
</script>
</body>
</html>