是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
在全局函数中,我们不能直接传递自定义值,但有很多方法,如下所示
var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf(item);//item: the value which you want to remove
//Method 1
ary.splice(index,1);
//Method 2
delete ary[index]; //in this method the deleted element will be undefined
其他回答
请不要使用带有delete的变体-它会在数组中留下一个洞,因为它不会在删除的项之后重新索引元素。
> Array.prototype.remove=function(v){
... delete this[this.indexOf(v)]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove("55");
undefined
> myarray
[ '3', '24', , '2' ]
真的,我不明白为什么不能用
arr = arr.filter(value => value !== 'seven');
或者你可能想使用普通的JS
arr = arr.filter(function(value) { return value !== 'seven' });
你可以像这样使用indexOf方法:
var index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
}
注意:对于IE8及以下版本,您需要对其进行填充
Var数组= [1,2,3,4] Var项= 3 var index = array.indexOf(item); 数组中。拼接(指数(1); console.log(数组)
我使用了投票最多的选项,并创建了一个函数,该函数将使用另一个不需要的单词数组清理一个单词数组:
function cleanArrayOfSpecificTerms(array,unwantedTermsArray) {
$.each(unwantedTermsArray, function( index, value ) {
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
});
return array;
}
要使用,请执行以下操作:
var notInclude = ['Not','No','First','Last','Prior','Next', 'dogs','cats'];
var splitTerms = ["call", "log", "dogs", "cats", "topic", "change", "pricing"];
cleanArrayOfSpecificTerms(splitTerms,notInclude)
var remove = function(array, value) {
var index = null;
while ((index = array.indexOf(value)) !== -1)
array.splice(index, 1);
return array;
};