javascript jQuery .each() 与 .map() 没有返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22519351/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:17:58  来源:igfitidea点击:

jQuery .each() vs. .map() without return

javascriptjquerymapeach

提问by neridaj

Is there any difference between .each() and .map() when no value is returned? Is there any benefit in using one or the other in this case?

当没有返回值时 .each() 和 .map() 之间有什么区别吗?在这种情况下使用一种或另一种有什么好处吗?

myList.map(function(myModel, myIndex){              
    myModel.itemOne = itemOne;
    myModel.itemTwo = itemTwo;
    myModel.itemThree = itemThree;
});

myList.each(function(myModel, myIndex){             
    myModel.itemOne = itemOne;
    myModel.itemTwo = itemTwo;
    myModel.itemThree = itemThree;
});

采纳答案by jfriend00

.map()is designed to both iterate and create a new resulting array.

.map()旨在迭代并创建新的结果数组。

.each()is designed to be an iterator (no new array created).

.each()被设计为一个迭代器(没有创建新数组)。

Either will work for plain iteration, though I would argue that the intent of your code is clearer if you are just doing an iteration if you use .each()since that is its intended and only purpose.

两者都适用于普通迭代,但我认为如果您只是在进行迭代,那么您的代码的意图会更清晰,.each()因为这是它的预期目的和唯一目的。

As for functionality differences besides the creation of the array, jQuery's .each()allows you to terminate the iteration by returning falsefrom the callback. jQuery's .map()does not have a way to terminate the iteration.

至于除了创建数组之外的功能差异,jQuery.each()允许您通过false从回调返回来终止迭代。jQuery.map()没有办法终止迭代。

回答by jfriend00

Check out jQuery map vs. eachand https://learn.jquery.com/using-jquery-core/iterating/

查看jQuery map vs. eachhttps://learn.jquery.com/using-jquery-core/iterating/

In summary, it depends on what you want to do. $.each()uses the same array whereas $.map()returns a new one. The order of the passing argument is reversed in $.map()to match that of the native .map()method available in ECMAScript 5. It's not all about how you iterate through the arrays/object, but if and how the original array/object is modified. A plus is that with $.each()you can use the keyword thiswithin the function to reference the current element of the array/object.

总之,这取决于你想做什么。$.each()使用相同的数组,而$.map()返回一个新数组。传递参数的顺序颠倒过来$.map()以匹配.map()ECMAScript 5 中可用的本机方法的顺序。这不是关于如何迭代数组/对象,而是是否以及如何修改原始数组/对象。一个加号是$.each()您可以this在函数中使用关键字来引用数组/对象的当前元素。