您好,这个问题需要删除
答案 0 :(得分:2)
您可以使用filter
或reduce
,或者先使用slice
复制数组,然后执行splice
。
我个人很喜欢filter
,因为它简单易懂,意图明确
function removeItem(array, n) {
return array.filter((elem, i) => i !== n);
}
const original = [1,2,3,4];
console.log(removeItem(original, 1));
console.log(original);
function removeItem (array, n) {
return array.reduce((result, elem, i) => {
if (i !== n) result.push(elem);
return result;
}, [])
}
const original = [1,2,3,4];
console.log(removeItem(original, 1));
console.log(original);
function removeItem(array, n) {
const result = array.slice();
result.splice(n, 1);
return result;
}
const original = [1,2,3,4];
console.log(removeItem(original, 1));
console.log(original);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
答案 1 :(得分:1)
function removeItem(array, n) {
return array.filter((x, i) => i != n)
}
答案 2 :(得分:0)
var array = [2,1,3,5,6,8,9,7];
function removeArray(array,n){
array.splice(array.indexOf(n),1);
return array;
}
console.log(array);
array = removeArray(array, 6);
console.log(array);