主要知识点:
会返回新数组(或其他类型)
concat()、slice()、reverse()、toString()、join()
直接对数组进行修改
splice()、pop()、push()、sort()、unshift()、sort()
1 .slice()、concat()
function insert(arr, item, index) {
return arr.slice(0,index).concat(item,arr.slice(index));
}
2.偷粮换柱(还有其他的,这里只写一种)
function insert(arr, item, index) {
let a = arr.slice(0)
a.splice(index,0,item);
return a;
}
不能这样写:
function insert(arr, item, index) {
return arr.slice(0).splice(index,0,item);
}
原因:splice()如果第二个参数是0的话,就会返回一个空的数组,它是对数组本身进行操作的。