简体   繁体   English

JavaScript中forEach(function(tag))的含义

[英]Meaning of forEach(function(tag) in JavaScript

I came across the following code fragment in a CouchDB book . 我在CouchDB书中遇到了以下代码片段。

function(doc) {
  doc.tags && doc.tags.forEach(function(tag) {
    emit(tag, 1);
  });
}

Can some one explain how does the function(tag) part works? 可以解释一下功能(标签)部分如何工作吗?

Thanks and regards, 谢谢并恭祝安康,

raj 拉吉

This is called an anonymous inline function expression. 这称为匿名内联函数表达式。 It creates a function and gives you a reference to it, similar to if you had written: 它会创建一个函数并为您提供引用,类似于您编写的函数:

function emitTag(tag) {
    emit(tag, 1);
}
doc.tags && doc.tags.forEach(emitTag);

The array.forEach method calls the given function once for each of the items in array in order. array.forEach方法对array中的每个项目array.forEach调用给定的函数。 It is a standard method in ECMAScript Fifth Edition and has been in many browsers for some time, but not JScript (IE). 这是ECMAScript第五版中的标准方法,并且已经在许多浏览器中使用了一段时间,但不是JScript(IE)。 I am guessing couchdb takes care of that issue for you though. 我猜couchdb可以为您解决这个问题。

function(tag) {...} 

在“ doc.tags”中被称为“ for each”标记,并将“ tag”参数传递给相关的lambda函数。

forEach simply iterates over array and calls function you pass to it with every element it finds. forEach只是简单地遍历数组并调用您找到的每个元素传递给它的函数。

Be aware that not every browser support it, there's helper function $.forEach in jQuery, it is safer in terms of browser support. 请注意,并不是所有的浏览器都支持它,jQuery中有辅助函数$.forEach ,它在浏览器支持方面更安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM