javascript 使用 Underscore.js 从数组中删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19242439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:51:59  来源:igfitidea点击:

Removing Item from array with Underscore.js

javascriptunderscore.js

提问by MBehtemam

I have an array like this :

我有一个这样的数组:

var array = [1,20,50,60,78,90];
var id = 50;

How can i remove the id from the array and return a new array that does not have the value of the id in new array?

如何从数组中删除 id 并返回一个没有新数组中 id 值的新数组?

回答by Eugene Naydenov

For the complex solutions you can use method _.reject(), so that you can put a custom logic into callback:

对于复杂的解决方案,您可以使用 method _.reject(),以便您可以将自定义逻辑放入回调中:

var removeValue = function(array, id) {
    return _.reject(array, function(item) {
        return item === id; // or some complex logic
    });
};
var array = [1, 20, 50, 60, 78, 90];
var id = 50;
console.log(removeValue(array, id));

For the simple cases use more convenient method _.without():

对于简单的情况,使用更方便的方法_.without()

var array = [1, 20, 50, 60, 78, 90];
var id = 50;
console.log(_.without(array, id));

DEMO

演示

回答by Kevin Meredith

_filterworks too. It's the opposite of _reject.

_filter也有效。它与_reject相反。

var array = [1,20,50,60,78,90];
var id = 50;

var result = _.filter(array, function(x) { return x != id });

http://jsfiddle.net/kman007_us/WzaJz/5/

http://jsfiddle.net/kman007_us/WzaJz/5/

回答by timelyxyz

You can use splice, though it is not underscore's API:

您可以使用splice,尽管它不是下划线的 API:

arrayObject.splice(index,howmany,item1,.....,itemX)

In your example:

在你的例子中:

var index = _.indexOf(array, id);
array.splice(index, 1);