Underscore 的类似函数:_.contains vs. _.some 和 _.map vs _.each [英] Underscore's similar functions: _.contains vs. _.some and _.map vs _.each
问题描述
是否有理由使用一个而不是另一个?_.some 和 _.map 似乎更容易使用或适用于更多情况(根据我非常有限的经验),但从阅读它来看,它们听起来好像应该做同样的事情.我敢肯定还有其他实例,而且我对学习一些比较非常感兴趣.
Is there a reason to use one over the other? It seems that _.some and _.map are easier to use or applicable to more situations (from my very limited experience) but from reading it, they sound as if they should do the same thing. I'm sure there are other instances of this and I'm all ears on learning some of the comparisons.
推荐答案
_.contains
vs _.some
_.contains
vs _.some
_.contains
(_.contains(列表,值,[fromIndex])
如果该值存在于列表中,则返回 true
.如果列表是一个数组,则在内部使用 indexOf
.使用 fromIndex
在给定索引处开始搜索.
Returns
true
if the value is present in the list. UsesindexOf
internally, if list is an Array. UsefromIndex
to start your search at a given index.
_.some
(_.some(列表、[谓词]、[上下文]))
如果列表中的任何值通过谓词真值测试,则返回 true
.如果找到真正的元素,则短路并停止遍历列表.
Returns
true
if any of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a true element is found.
_.some
和 _.contains
的主要区别在于,contains
检查给定列表中是否存在给定项目some
检查列表中的任何元素是否满足传递的谓词.所以,他们都在做不同的任务.
The main difference between _.some
and _.contains
is that, contains
checks if a given item is present in the given list and some
checks if any of the elements in the list satisfies the predicate passed. So, they both are doing different tasks.
_.each
vs _.map
_.each
vs _.map
迭代一个元素列表,将每个元素依次产生给一个 iteratee 函数.
Iterates over a list of elements, yielding each in turn to an iteratee function.
通过转换函数 (iteratee) 映射列表中的每个值,生成一个新的值数组.
_.map
调用传递的函数(iterateecode>) 与列表的每个元素创建一个新的 Array 对象,但是
_.each
简单地使用每个元素调用传递的函数 (iteratee
)(注意:这不会创建数组).
_.map
calls the function passed (iteratee
) with each and every element of the list to create a new Array object, but _.each
simply calls the function passed (iteratee
) with each and every element (Note: this doesn't create an Array).
基本上 _.each
是 for (var i = 0; i
Basically _.each
is the functional equivalent of for (var i = 0; i < array.length; i += 1) {...}
. Again, they both are doing different jobs.
这篇关于Underscore 的类似函数:_.contains vs. _.some 和 _.map vs _.each的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!