简体   繁体   English

在JavaScript中,forEach回调如何在后台运行? 有收益声明吗?

[英]How does the forEach callback work behind the scenes in javascript? Is there a yield statement?

In javascript, I realize that the callback function is passed each element of the collection in a forEach method call, but how does it have access to it? 在javascript中,我意识到回调函数是通过forEach方法调用传递给集合的每个元素的,但是如何访问它呢? In Ruby, we yield to the block. 在Ruby中,我们屈服于块。

def calculation(a, b)
  yield(a, b)
end

puts calculation(5, 6) { |a, b| a + b } # addition
puts calculation(5, 6) { |a, b| a - b } # subtraction

But in Javascript, how does the function get passed each element of the array? 但是在Javascript中,该函数如何传递给数组的每个元素? What's going on behind the scenes with the built in forEach function? 内置的forEach函数在幕后发生了什么?

fruits.forEach(function (item, index, array) {
  console.log(item, index);
});

Well, it's not that hard to implement more easily than its done in the reference : 好吧,比起参考中的实现,实现起来并不难:

function forEach(fn) {
    for (var i = 0; i < this.length; ++i) { // 'this' is the array, of course
        fn(this[i], i, this);
    }
}

I've also removed thisArg for simplicity's sake 为了简单起见,我也删除了thisArg

The actual implementations do more checking and are more robust, but this illustrates the idea, I think. 实际的实现会进行更多的检查并且更加健壮,但是我认为这说明了这一想法。 I can imagine it being implemented natively, as well. 我可以想象它也在本地实现。

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

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