2013-10-03 48 views
0

为什么将一个匿名函数传入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" 

回答

2

如果使用squareIt(x)而是直接调用函数,并传递作为参数的返回值,你应该通过函数本身

arr.map(squareIt); 

在你的情况,因为当你调用函数

0

传递函数工作正常x没有定义,你得到了一个额外的错误,但是当你在通参数中使用(),它会立即调用函数:

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

正确的方法是使用一个匿名函数,并与参数调用你的函数:

otherItems = arr.map(function() { 
    squareIt(x); 
}); 
0

这是因为函数表达式立即执行。所以当它试图调用SquareIt(X)时,它找不到X,因此你会得到异常"Uncaught ReferenceError: x is not defined"。尝试呼叫之前定义X,说x = 4;

,那么你将得到一个异常

Uncaught TypeError: 16 is not a function 

因为Map函数需要一个函数作为参数,而不是一个整数。

当您将功能传递出()时,您有点传递回调。