是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
你可以使用lodash的拉函数
Var ary = [' 3 ', ' 7 ', ' 11 ']; _。拉(氩,' 7 ');// [' 3 ', ' 11 '] console.log(必要) < script src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js " > < /脚本>
其他回答
非破坏性拆卸:
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;
};
在所有唯一的值中,您可以:
a = new Set([1,2,3,4,5]) // a = Set(5) {1, 2, 3, 4, 5}
a.delete(3) // a = Set(5) {1, 2, 4, 5}
[...a] // [1, 2, 4, 5]
最简单的解决方案是:
array—用于删除某些元素的数组valueForRemove; valueForRemove—用于删除的元素;
array.filter(arrayItem => !array.includes(valueForRemove));
更简单:
array.filter(arrayItem => arrayItem !== valueForRemove);
不漂亮,但有用:
array.filter(arrayItem => array.indexOf(arrayItem) != array.indexOf(valueForRemove))
不漂亮,但有用:
while(array.indexOf(valueForRemove) !== -1) {
array.splice(array.indexOf(valueForRemove), 1)
}
附注:filter()方法创建一个包含所有通过所提供函数实现的测试的元素的新数组。参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
一个非常干净的解决方案工作在所有浏览器,没有任何框架是分配一个新的数组,并简单地返回它没有你想删除的项:
/**
* @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;
}