是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
诀窍是从头到尾遍历数组,这样在删除元素时就不会弄乱下标。
var deleteMe = function( arr, me ){
var i = arr.length;
while( i-- ) if(arr[i] === me ) arr.splice(i,1);
}
var arr = ["orange","red","black", "orange", "white" , "orange" ];
deleteMe( arr , "orange");
Arr现在是[红的,黑的,白的]
其他回答
var index = array.indexOf('item');
if(index!=-1){
array.splice(index, 1);
}
你可以用以下两种方法:
const arr = ['1', '2', '3', '4'] // we wanna delete number "3"
第一种方式: arr.indexOf (3) ! = = 1 & & arr.splice (arr.indexOf (3), 1) 第二种方式(ES6)特别无突变: const newArr = arr。过滤(e => e !== '3')
方法1
var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf('seven'); // get index if value found otherwise -1
if (index > -1) { //if found
ary.splice(index, 1);
}
方法2
一条衬垫
var ary = ['three', 'seven', 'eleven'];
filteredArr = ary.filter(function(v) { return v !== 'seven' })
// Or using ECMA6:
filteredArr = ary.filter(v => v !== '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;
}
这样看看:
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');