FED64. 添加元素
描述
在数组 arr 的 index 处添加元素 item。不要直接修改数组 arr,结果返回新的数组示例1
输入:
[1, 2, 3, 4], 'z', 2
输出:
[1, 2, 'z', 3, 4]
HTML/CSS/JavaScript 解法, 执行用时: 826ms, 内存消耗: 77772KB, 提交时间: 2020-10-30
{"css":"","js":"function insert(arr, item, index) {\n let arr1 = []\n for (let i =0; i<arr.length;i++){\n arr1.push(arr[i])\n \n }\n arr1.splice(index,0,item)\n return arr1\n}","html":"","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 854ms, 内存消耗: 77772KB, 提交时间: 2020-12-20
{"css":"","js":"function insert(arr, item, index) {\n let result = arr.slice();\n result.splice(2,0,item);\n return result;\n}","html":"","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 856ms, 内存消耗: 77772KB, 提交时间: 2020-12-27
{"css":"","js":"function insert(arr, item, index) {\n var newArr = arr.slice(0);\n newArr.splice(index,0,item);\n return newArr\n\n}","html":"","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 856ms, 内存消耗: 77788KB, 提交时间: 2021-05-21
{"css":"","js":"function insert(arr, item, index) {\n return arr.reduce((c,v,i)=>{\n \n if(i == index){\n c.push(item,v)\n }else{c.push(v)}\n return c\n },[])\n}","html":"","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 856ms, 内存消耗: 77812KB, 提交时间: 2021-03-14
{"css":"","js":"function insert(arr, item, index) {\n let bb = []\n for(let i=0;i<arr.length+1;i++){\n if(i>=index){\n if(i==index){bb[i]=item}\n else{bb[i]=arr[i-1]}\n }else{\n bb[i]=arr[i]\n }\n }\n return bb\n}","html":"","libs":[]}