返回一个函数——没有记录到控制台
Returning a Function - Nothing logging to the console
我无法看出我在编写此 'transformArray' 函数时哪里出错了。我试图让它接受一个函数作为参数,将它应用于某个数组的每个元素。为什么它 return 什么都没有?
var array1 = [1,2,3,4,5];
function transformArray (aFunction) {
return function (array) {
return array.forEach(aFunction);
};
}
var halve = transformArray(function (num) {return num/2;});
console.log(halve(array1));
那是因为 Array.forEach
是一个迭代器。它总是 returns undefined
.
MDN: forEach()
executes the callback function once for each array element;
unlike every()
and some()
it, always returns the value undefined.
你需要的是Array.map
The map()
method creates a new array with the results of calling a
provided function on every element in this array.
function transformArray (aFunction) {
return function(array) {
return array.map(aFunction);
};
}
(强调我的)
我无法看出我在编写此 'transformArray' 函数时哪里出错了。我试图让它接受一个函数作为参数,将它应用于某个数组的每个元素。为什么它 return 什么都没有?
var array1 = [1,2,3,4,5];
function transformArray (aFunction) {
return function (array) {
return array.forEach(aFunction);
};
}
var halve = transformArray(function (num) {return num/2;});
console.log(halve(array1));
那是因为 Array.forEach
是一个迭代器。它总是 returns undefined
.
MDN:
forEach()
executes the callback function once for each array element; unlikeevery()
andsome()
it, always returns the value undefined.
你需要的是Array.map
The
map()
method creates a new array with the results of calling a provided function on every element in this array.
function transformArray (aFunction) {
return function(array) {
return array.map(aFunction);
};
}
(强调我的)