1.利用slice+concat**
function insert(arr, item, index) {
return arr.slice(0,index).concat(item,arr.slice(index));
}
2.利用concat +splice
function insert(arr, item, index) {
var newArr=arr.concat();
newArr.splice(index,0,item);
return newArr;
}
3.利用slice+splice
function insert(arr, item, index) {
var newArr=arr.slice(0);
newArr.splice(index,0,item);
return newArr;
}
4.利用push.apply+splice
function insert(arr, item, index) {
var newArr=[];
[].push.apply(newArr, arr);
newArr.splice(index,0,item);
return newArr;
}
有其他欢迎补充,相互学习
在数组 arr 的 index 处添加元素 item。不要直接修改数组 arr,结果返回新的数组
最新推荐文章于 2021-08-04 17:36:25 发布