从underscorejs中的循环数组中删除项目

问题描述 投票:1回答:5

我有这样的数组

var array = [1,2,3,4,5,6,7,8,9,10];

使用_.each中的underscore.js函数循环代码就像这样

_.each(array,function(item,index){
  console.log(item);
});

但是我希望在循环时删除数组中的一些项目。例如,我需要从数组中删除数字5并且循环不打印数字5.问题是,是否可以在此数组上循环时删除数组中的项目?

javascript arrays underscore.js
5个回答
1
投票

使用下划线,您可以这样做:

var array = [1,2,3,4,5,6,7,8,9,10];

var filteredList = _.filter(array, function(item){

    // do something with each item - here just log the item
    console.log(item);

    // only want even numbers
    return item % 2 == 0;

});

// show filtered list
_.each(filteredList, function(item){
    console.log(item);
});

4
投票

在迭代它时修改数组通常是一个非常糟糕的主意。最好的解决方案是将索引存储在一个单独的数组中并在之后删除它们(记得从最后一个到第一个迭代该数组,这样您就不必处理更改索引)。


2
投票

2种方式,我推荐第一种方法。

var array = [1,2,3,4,5,6,7,8],
    items_to_remove = [], i;

_.each(array, function(item,index){
    if(item === 'something'){
        items_to_remove.push(index);
    }
});

while((i = items_to_remove.pop()) != null){
    array.splice(i, 1);
}

// OR
for(i = array.length - 1; i > -1; --i) {
    if(array[i] === 'something') {
        array.splice(i, 1);
    }
}

1
投票

您可以使用Underscore来减少代码行。 Underscore是一个方便的工具。

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
array = _.without(array, _.findWhere(array, {
  id: 3
}));
console.log(arr);

1
投票

这是一个简单的内联解决方案,使用下划线的拒绝功能为我工作:

_.each(_.reject(array, function(arrayItem) { return arrayItem === 5}), function(item){
  console.log(item);
});
© www.soinside.com 2019 - 2024. All rights reserved.