1

为什么将匿名函数传递给map函数可以工作,但尝试传递函数表达式会引发错误?

arr = [2,4,6,8];

items = arr.map(function(x) {
  return Math.pow(x, 2);
});

console.log(items);  // Returns [4, 16, 36, 64]

squareIt = function(x) {
  return Math.pow(x, 2);
}

otherItems = arr.map(squareIt(x));

console.log(otherItems);  // Returns "Uncaught ReferenceError: x is not defined"
4

3 回答 3

2

您应该传递函数本身

arr.map( squareIt ); 

如果squareIt(x)改为使用,则直接调用该函数并将其返回值作为参数传递。

在您的情况下,您遇到了一个额外的错误,因为x在您调用函数时未定义

于 2013-10-03T13:16:06.543 回答
0

It's because function expression are executed immediately. So when it tries to invoke SquareIt(X), it can not find X and hence you get the exception "Uncaught ReferenceError: x is not defined". Try defining X before the call, say x = 4;

you will then get an exception

Uncaught TypeError: 16 is not a function 

because the Map function expects a function as an argument, not an integer.

When you pass function with out () , you are kind of passing a callback.

于 2013-10-03T13:18:12.110 回答
0

传递函数可以正常工作,但是当您()在 pass 参数中使用时,它会立即调用该函数:

otherItems = arr.map(squareIt(x)); <---Invoked immediately!

正确的方法是使用匿名函数并使用参数调用您的函数:

otherItems = arr.map(function() {
    squareIt(x);
});
于 2013-10-03T13:17:34.940 回答