是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
当你需要移除一个在数组中多次出现的值时(例如。[1,2,2,2,4,5,6])。
function removeFrmArr(array, element) {
return array.filter(e => e !== element);
};
var exampleArray = [1,2,3,4,5];
removeFrmArr(exampleArray, 3);
// return value like this
//[1, 2, 4, 5]
可以使用splice从数组中删除单个元素,但splice不能从数组中删除多个相似的元素。
function singleArrayRemove(array, value){
var index = array.indexOf(value);
if (index > -1) array.splice(index, 1);
return array;
}
var exampleArray = [1,2,3,4,5,5];
singleArrayRemove(exampleArray, 5);
// return value like this
//[1, 2, 3, 4, 5]
其他回答
这样看看:
delete this.arrayName[this.arrayName.indexOf(value)];
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
这样看看:
for(var i in array){
if(array[i]=='seven'){
array.splice(i,1);
break;
}
}
在函数中:
function removeItem(array, item){
for(var i in array){
if(array[i]==item){
array.splice(i,1);
break;
}
}
}
removeItem(array, 'seven');
非破坏性拆卸:
function removeArrayValue(array, value)
{
var thisArray = array.slice(0); // copy the array so method is non-destructive
var idx = thisArray.indexOf(value); // initialise idx
while(idx != -1)
{
thisArray.splice(idx, 1); // chop out element at idx
idx = thisArray.indexOf(value); // look for next ocurrence of 'value'
}
return thisArray;
}
ES6路。
const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);
在全局函数中,我们不能直接传递自定义值,但有很多方法,如下所示
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