从下划线中的数组中删除值 [英] Remove value from array in Underscore
问题描述
为什么下划线没有超级简单的remove
函数?
Why isn't there a super simple remove
function in underscore?
var arr = [1,2,3,4,5];
_.remove(arr, 5);
当然我可以使用 reject
或 without
......但它们都不是破坏性的.我错过了什么吗?
Sure I could use reject
or without
... but neither of them are destructive. Am I missing something?
我想我会用老式的方式来做...
I guess I'll do it the old fashioned way...
arr.splice(arr.indexOf(5), 1);
呃
推荐答案
说明
这是因为 Underscore 为 JavaScript 提供了函数式概念,而函数式编程的关键概念之一是 参考透明度.
本质上,函数没有副作用,并且对于给定的输入总是返回相同的输出.换句话说,所有函数都是纯.
Essentially, functions do not have side-effects and will always return the same output for a given input. In other words, all functions are pure.
从数组中移除元素确实是给定输入的可预测结果,但结果将是副作用而不是返回值.因此,破坏性函数不适合函数范式.
Removing an element from the array would indeed be a predictable result for the given input, but the result would be a side-effect rather than a return value. Thus, destructive functions do not fit into the functional paradigm.
已在 Stack Overflow 此处上详细讨论了从 Underscore 中的数组中删除值的正确方法.作为旁注,当使用 without
、reject
或 filter
时,如果您只想从数组中删除一个项目的单个实例,您将需要唯一标识它.所以,以这种方式:
The correct way to remove values from an array in Underscore has already been discussed at length on Stack Overflow here. As a side note, when using without
, reject
or filter
, if you only want to remove a single instance of an item from an array, you will need to uniquely identify it. So, in this manner:
arr = _.without(arr, 5);
您将从arr
中删除所有5
的实例.
这篇关于从下划线中的数组中删除值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!