javascript - Array.prototype.map() 的callback如何使用调用map的函数的变量?
本文介绍了javascript - 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 错误。
解决方案
function fn(count) {
return function(val) {
return count + val;
}
}
function a(count) {
var cb = fn(count);
return [1, 2, 3].map(cb);
}
这篇关于javascript - Array.prototype.map() 的callback如何使用调用map的函数的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文