练习牛客网笔试题--前端js--20-添加元素-index处
// 题目描述
// 在数组 arr 的 index 处添加元素 item。不要直接修改数组 arr,结果返回新的数组
// 输入 [1, 2, 3, 4], 'z', 2
// 输出 [1, 2, 'z', 3, 4]
1.自己的练习
1.剩余参数+splice
function insert(arr, item, index) {
var newArr = [...arr];
newArr.splice(index, 0, item);
return newArr;
}
2.剩余参数+slice
function insert(arr, item, index) {
var newArr1 = arr.slice(0, index);
var newArr2 = arr.slice(index);
return [...newArr1, item, ...newArr2];
}
3.剩余参数+concat
function insert(arr, item, index) {
var newArr1 = arr.slice(0, index);
var newArr2 = arr.slice(index);
return newArr1.concat(item).concat(newArr2);
}
2.题解
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;
}