问题描述
我之前在这里回答了有关的问题如何获得JSON的响应数?,我建议他们使用 map
函数,而不要使用 for
循环,但是有人评论了.map
不用于循环,而应使用 forEach
.
I've answered a question here before about How to get number of response of JSON? and I suggested for them to use the map
function instead of using a for
loop but someone commented that .map
is not for looping and to use forEach
instead.
在 for
循环上使用 map
是否有不利之处?
Are there any downsides to using map
over a for
loop?
我也对此进行了研究,发现了网站,说明该 map
> forEach
.
I also researched this and found a site stating that map
> forEach
.
推荐答案
Map用于将数组中的每个元素转换为另一个表示形式,并以新的顺序返回结果.但是,由于对每个项目都调用了该函数,因此您可能可以进行任意调用而什么也不返回,因此尽管严格说来它们并不相同,但它的行为就像 forEach
一样.
Map is used to transform each element in an array into another representation, and returns the results in a new sequence. However, since the function is invoked for each item, it is possible that you could make arbitrary calls and return nothing, thus making it act like forEach
, although strictly speaking they are not the same.
正确使用map(将值的数组转换为另一种表示形式):
Proper use of map (transforming an array of values to another representation):
var source = ["hello", "world"];
var result = source.map(function(value) {
return value.toUpperCase();
});
console.log(result); // should emit ["HELLO, "WORLD"]
偶然使用 .map
进行迭代(语义错误):
Accidentally using .map
to iterate (a semantic error):
var source = ["hello", "world"];
// emits:
// "hello"
// "world"
source.map(function(value) {
console.log(value);
});
第二个示例在技术上是有效的,它将编译并运行,但这不是 map
的预期用途.
The second example is technically valid, it'll compile and it'll run, but that is not the intended use of map
.
谁在乎,是否满足我的要求?"可能是您的下一个问题.首先, map
会忽略索引中具有指定值的项目.另外,由于 map
期望返回结果,因此它正在做额外的事情,从而为一个简单的进程分配了更多的内存和处理时间(尽管很短).更重要的是,这可能会使您自己或其他开发人员混淆您的代码.
"Who cares, if it does what I want?" might be your next question. First of all, map
ignores items at an index that have an assigned value. Also, because map
has an expectation to return a result, it is doing extra things, thus allocating more memory and processing time (although very minute), to a simple process. More importantly, it may confuse yourself or other developers maintaining your code.
这篇关于.map不用于循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!