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
Removing Item from array with Underscore.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));
回答by Kevin Meredith
_filterworks too. It's the opposite of _reject.
var array = [1,20,50,60,78,90];
var id = 50;
var result = _.filter(array, function(x) { return x != id });
回答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);