javascript Lodash 从字符串数组中删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30486534/
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
Lodash remove from string array
提问by just-boris
I have an array of string and want to instantly remove some of them. But it doesn't work
我有一个字符串数组,想立即删除其中的一些。但它不起作用
var list = ['a', 'b', 'c', 'd']
_.remove(list, 'b');
console.log(list); // 'b' still there
I guess it happened because _.remove
function accept string as second argument and considers that is property name. How to make lodash do an equality check in this case?
我猜这是因为_.remove
函数接受字符串作为第二个参数并认为这是属性名称。在这种情况下如何让 lodash 进行相等性检查?
回答by trevor
One more option for you is to use _.pull, which unlike _.without, does not create a copy of the array, but only modifies it instead:
另一个选择是使用 _.pull,它与 _.without 不同,它不会创建数组的副本,而只会修改它:
_.pull(list, 'b'); // ['a', 'c', 'd']
Reference: https://lodash.com/docs#pull
回答by Retsam
As Giuseppe Pes points out, _.remove
is expecting a function. A more direct way to do what you want is to use _.without
instead, which doestake elements to remove directly.
正如 Giuseppe Pes 指出的那样,_.remove
期待一个功能。做你想做的更直接的方法是使用_.without
,它确实需要直接删除元素。
_.without(['a','b','c','d'], 'b'); //['a','c','d']
回答by Giuseppe Pes
Function _.remove doesn't accept a string as second argument but a predicate function which is called for each value in the array. If the function returns true
the value is removed from the array.
函数 _.remove 不接受字符串作为第二个参数,而是接受为数组中的每个值调用的谓词函数。如果函数返回true
,则从数组中删除该值。
Lodas doc: https://lodash.com/docs#remove
Lodas 文档:https://lodash.com/docs#remove
Removes all elements from array that predicate returns truthy for and returns an array of the removed elements. The predicate is bound to thisArg and invoked with three arguments: (value, index, array).
从数组中删除谓词返回真值的所有元素,并返回已删除元素的数组。谓词绑定到 thisArg 并使用三个参数调用:(值、索引、数组)。
So, if you want to remove b
from your array you should something like this:
所以,如果你想b
从你的数组中删除你应该是这样的:
var list = ['a', 'b', 'c', 'd']
_.remove(list, function(v) { return v === 'b'; });
["a", "c", "d"]