在数组 arr 的 index 处添加元素 item。不要直接修改数组 arr,结果返回新的数组
添加元素
http://www.nowcoder.com/questionTerminal/941bcfa5b87940869fda681c1597fd3a
1、利用es6扩展运算符:
function insert(arr, item, index) {
let newArr = [...arr];
newArr.splice(index, 0, item);
return newArr;
} 2、利用slice返回新数组的特性:
function insert(arr, item, index) {
let newArr = arr.slice(0);
newArr.splice(index, 0, item);
return newArr;
} 3、利用concat返回新数组的特性:
function insert(arr, item, index) {
let newArr = arr.concat();
newArr.splice(index, 0, item);
return newArr;
}
查看13道真题和解析