是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
一行代码就可以了,
var arr = ['three', 'seven', 'eleven'];
// Remove item 'seven' from array
var filteredArray = arr.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]
// In ECMA6 (arrow function syntax):
var filteredArray = arr.filter(e => e !== 'seven')
这就使用了JS中的filter函数。它在IE9及更高版本中得到支持。
它的功能(来自文档链接)
Filter()为数组中的每个元素调用一次所提供的回调函数,并构造一个包含所有回调返回强制为true的值的新数组。回调只对数组中已赋值的索引调用;对于已删除或从未赋值的索引,不调用该方法。未通过回调测试的数组元素将被跳过,并且不包含在新数组中。
基本上,这和所有其他for (var key in ary){…}解决方案,除了从IE6开始支持for in构造。
基本上,filter是一个方便的方法,与for in构造(AFAIK)相比,它看起来更好(并且是可链的)。
其他回答
鉴于没有一个漂亮的ES6函数,这里有一个简单且可重用的ES6函数。
const removeArrayItem = (arr, itemToRemove) => {
return arr.filter(item => item !== itemToRemove)
}
用法:
const items = ['orange', 'purple', 'orange', 'brown', 'red', 'orange']
removeArrayItem(items, 'orange')
CoffeeScript + jQuery变体:
arrayRemoveItemByValue = (arr,value) ->
r=$.inArray(value, arr)
unless r==-1
arr.splice(r,1)
# return
arr
console.log arrayRemoveItemByValue(['2','1','3'],'3')
它只移除一个,而不是全部。
一个非常干净的解决方案工作在所有浏览器,没有任何框架是分配一个新的数组,并简单地返回它没有你想删除的项:
/**
* @param {Array} array the original array with all items
* @param {any} item the time you want to remove
* @returns {Array} a new Array without the item
*/
var removeItemFromArray = function(array, item){
/* assign a empty array */
var tmp = [];
/* loop over all array items */
for(var index in array){
if(array[index] !== item){
/* push to temporary array if not like item */
tmp.push(array[index]);
}
}
/* return the temporary array */
return tmp;
}
非破坏性拆卸:
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;
}
var remove = function(array, value) {
var index = null;
while ((index = array.indexOf(value)) !== -1)
array.splice(index, 1);
return array;
};