2

I am having trouble trying to understand the code below. I'm coming from a Java background. How should I read this? Is there any good Java > Javascript books/tutorials I should be looking at?

function sum(numbers) {
   var total = 0;

   forEach(numbers, function (number) {
      total += number;
   });

   return total;
}
show(sum([1, 10, 100]));

Extracted from http://eloquentjavascript.net/chapter6.html

I'm looking at the forEach(numbers, function (number)... code. Where will the anonymous function get the 'number' from?

4

3 回答 3

5

查看源代码forEach

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}

forEach接受两个参数:一个数组和一个回调(即一个函数)。您可以看到它在循环中调用回调,每次都将“当前”数组元素作为参数传递给它。number这就是回调的形式参数中的内容。

换句话说——你可以很容易地理解这一点:

function hello(what) {
    alert("Hello " + what);
}

hello("world");

如果您将hello其用作回调,您将获得与您显示的代码非常相似的代码:

function say(callback, what) {
    callback(what);
}

say(hello, "world");

看到它在行动

最后,您可能会从检查回调如何工作以及它们的用途中受益;是我关于这个主题的另一个答案。

于 2013-05-30T08:10:14.640 回答
2

它从数字中获取数字。foreach 所说的是,对于 numbers 中的每个元素,使用该元素调用匿名函数。然后那个元素被称为数字,但它可以被称为任何东西。

于 2013-05-30T08:10:02.703 回答
1

您感到困惑的是,您没有看到 forEach 的底层机制...如果您将其撬开,您会看到该函数需要一个匿名函数作为其第二个参数,并且它将传递任何它需要进入 IT 领域。因此,您可以期望在运行函数时填充该参数。当你用不同的语言来处理它时,这绝对是不和谐的,但你必须相信事情会按照它们设计的方式工作。

于 2013-05-30T08:14:29.447 回答