gpt4 book ai didi

javascript - Underscore 的类似函数 : _. 包含 vs. _.some 和 _.map vs _.each

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:54:42 25 4
gpt4 key购买 nike

是否有理由使用一个而不是另一个?似乎 _.some 和 _.map 更易于使用或适用于更多情况(根据我非常有限的经验),但从阅读它来看,它们听起来好像应该做同样的事情。我敢肯定还有其他这样的例子,我很乐意学习其中的一些比较。

最佳答案

_.contains对比_.some

_.contains (_.contains(list, value, [fromIndex])

Returns true if the value is present in the list. Uses indexOf internally, if list is an Array. Use fromIndex to start your search at a given index.

_.some (_.some(list, [predicate], [context]))

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检查列表中的任何元素是否满足传递的谓词。因此,他们都在执行不同的任务。

_.each对比_.map

_.each (_.each(list, iteratee, [context])

Iterates over a list of elements, yielding each in turn to an iteratee function.

_.map (_.map(list, iteratee, [context])

Produces a new array of values by mapping each value in list through a transformation function (iteratee).

_.map 使用列表的每个元素调用传递的函数 ( iteratee ) 以创建一个新的 Array 对象,但是 _.each 只需对每个元素调用传递的函数 ( iteratee )(注意:这不会创建数组)。

基本上_.eachfor (var i = 0; i < array.length; i += 1) {...} 的功能等价物.同样,他们都在做不同的工作。

关于javascript - Underscore 的类似函数 : _. 包含 vs. _.some 和 _.map vs _.each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28759010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com