如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
我找到了这个博客文章,
9 从 JavaScript 阵列中删除元素的方法 - 附加如何安全清除 JavaScript 阵列
我更喜欢用filter()
:
var filtered_arr = arr.filter(function(ele){
return ele != value;
})
其他回答
var array = [2, 5, 9];
var res = array.splice(array.findIndex(x => x==5), 1);
console.log(res)
使用 Array. findindindex, 我们可以减少代码行数。
这是我的简单的代码,用来用复盘方法。复数法将被给定两个参数。第一个参数是起始数,第二个参数是删除Count。第二个参数用于从第一个参数的值开始删除某些元素。
let arr = [1, 3, 5, 6, 9];
arr.splice(0, 2);
console.log(arr);
**simple array**
const arr = ['1','2','3'];
const updatedArr = arr.filter(e => e !== '3');
console.warn(updatedArr);
**array of object**
const newArr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]
const updatedNewArr = newArr.filter(e => e.id !== 3);
console.warn(updatedNewArr);
**array of object with different parameter name**
const newArr = [{SINGLE_MDMC:{id:1,cout:10}},{BULK_MDMC:{id:1,cout:15}},{WPS_MDMC:{id:2,cout:10}},]
const newArray = newArr.filter((item) => !Object.keys(item).includes('SINGLE_MDMC'));
console.log(newArray)
OK,OK, OK, OK, OK, OK, OK, OK, OK,OK, OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,例如,您有下面的数组:
var num = [1, 2, 3, 4, 5];
我们想要删除第4号, 你可以简单地使用下面的代码:
num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];
如果您正在重复使用此函数,请写入一个可重复使用的函数,该函数将附于原土类似以下的数组函数 :
Array.prototype.remove = Array.prototype.remove || function(x) {
const i = this.indexOf(x);
if(i===-1)
return;
this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}
但如果您有下面的数组, 而不是数组中的几个 [5] 呢?
var num = [5, 6, 5, 4, 5, 1, 5];
我们需要一个循环来检查它们, 但是一个更容易和更有效的方法是使用内置的 JavaScript 函数, 所以我们写一个函数, 使用下面这样的过滤器 :
const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]
还有第三方图书馆,如Lodash 或Goint, 也帮助你这样做。更多信息,请参看 Lodash _. pull,_. pullAt 或_。
您可以使用ES6. 例如,在此情况下删除值“ 3” :
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);
产出:
["1", "2", "4", "5", "6"]