如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
不可改变和一班制方式:
const newArr = targetArr.filter(e => e !== elementToDelete);
其他回答
使用欧 6扩展操作员 。
比方说你想删除4。
let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]
我喜欢这个单行道:
arr.includes(val) && arr.splice(arr.indexOf(val), 1)
null
或undefined
作为原型
// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}
(是的,我读了所有其他的答案 却找不到一个结合的答案)includes
和splice
在同一行中。 )
spolice () 函数能够将数组中的项目还给您, 从特定的索引中删除项目 / 项 :
function removeArrayItem(index, array) {
array.splice(index, 1);
return array;
}
let array = [1,2,3,4];
let index = 2;
array = removeArrayItem(index, array);
console.log(array);
减少方法的利润如下:
(a) 需要按索引删除某一要素:
function remove(arr, index) {
return arr.reduce((prev, x, i) => prev.concat(i !== index ? [x] : []), []);
}
b) 需要删除元素值(int)的元素:
function remove(arr, value) {
return arr.reduce((prev, x, i) => prev.concat(x !== value ? [x] : []), []);
}
这样我们就可以返回一个新的阵列( 将会以酷酷的功能方式- 比使用推或组合要好得多) , 并删除元素 。
使用数组过滤过滤器方法 :
let array = [1, 2, 3, 4, 511, 34, 511, 78, 88];
let value = 511;
array = array.filter(element => element !== value);
console.log(array)