[英]Why does this anonymous function return undefined in Javascript?
I'm trying to create a forEach()
function that takes an array and a function, then performs the function action on each element of the array. 我正在尝试创建一个带数组和一个函数的forEach()
函数,然后对数组的每个元素执行函数动作。 However, when trying to pass the below anonymous function, I get undefined
. 但是,当尝试传递以下匿名函数时,我得到undefined
。 I tried adding a return
to the forEach()
function after reading some other posts but then the function doesn't run at all and just returns the first array[i]
it receives without modifying it. 在阅读了其他一些文章后,我尝试在forEach()
函数中添加return
,但是该函数完全不运行,仅返回它收到的第一个array[i]
而不修改它。
function forEach(array, action){
for(var i = 0; i < array.length; i++)
action(array[i]);
}
var myArray = [1, 2, 3];
var something = forEach(myArray, function(element){return element++;});
console.log(something)
//undefined
That returns undefined
. 返回undefined
。
function forEach(array, action){
for(var i = 0; i < array.length; i++)
return action(array[i]);
}
var myArray = [1, 2, 3];
var something = forEach(myArray, function(element){return element++;});
console.log(something)
//undefined
That returns 1
. 返回1
。
What am I missing? 我想念什么?
(I am aware a .forEach() function exists, I am trying this as a learning exercise) (我知道存在一个.forEach()函数,我正在尝试将其作为学习练习)
Your forEach
function doesn't return anything. 您的forEach
函数不返回任何内容。 It looks like you're trying your hand at a map
implementation. 看来您正在尝试实施map
。 If so, you need to add your results to a new array and return that array. 如果是这样,则需要将结果添加到新数组中并返回该数组。
function map(array, action) { // Renamed forEach to a more suitable name
var results = [];
for (var i = 0; i < array.length; i++) {
results.push(action(array[i]));
}
return results;
}
Your foreach
implementation is correct - it shouldn't return anything. 您的foreach
实现是正确的-它不应返回任何内容。 If you want map
(ie transform an argument into a new array), you can implement reduce
first: 如果要map
(即将参数转换为新数组),则可以先实现reduce
:
function reduce(array, action, result) {
forEach(array, function (elem) {
result = action(result, elem);
});
return result;
}
and then, define map
via reduce
: 然后,通过reduce
定义map
:
function map(array, action) {
return reduce(array, function (result, elem) {
return result.concat(action(elem));
}, []);
}
Putting it all together: 放在一起:
function forEach(array, action) { for (var i = 0; i < array.length; i++) action(array[i]); } function reduce(array, action, result) { forEach(array, function (elem) { result = action(result, elem); }); return result; } function map(array, action) { return reduce(array, function (result, elem) { return result.concat(action(elem)); }, []); } a = map([1, 2, 3, 4], function (x) { return ++x }); document.write('<pre>' + JSON.stringify(a, 0, 3));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.