猿问

Array.prototype.map() 的callback如何使用调用map的函数的变量?

function a(count) {  return [1,2,3].map(val => val + count);
}function b(count) {  return [1,2,3].map(fn);
}function fn(val) {  return val + count;
}console.log('a' + a(9));console.log('b' + b(9));

Function a中,map的callback使用arrow function直接定义在function a中,那么map的callback是可以使用count变量的。

如果我想复用map的callback函数,如function b,那么这个callback如何取得count的值呢? 如上面的代码,会抛出ReferenceError: count is not defined 错误。


茅侃侃
浏览 649回答 1
1回答

慕容3067478

function fn(count) {    return function(val) {        return count + val;    }}function a(count) {    var cb = fn(count);    return [1, 2, 3].map(cb);}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答