I'm working through Eloquent Javascript and there's an exercise to make an every
function, which takes an array and a function and returns true or false depending on what all the items in the array return after going through the function.
I'm confused because when I do console.log() within the function, I get the boolean twice...but when I do console.log(every(arr, func)), I get undefined
.
var every = function(arr, req){
arr.map(function(item){
return req(item);
}).reduce(
function(total, num){
// this returns: true
// true
console.log(total && num);
return total && num;
});
}
// This returns undefined
console.log(every([NaN, NaN, NaN], isNaN));
So why do I get true
twice inside my function, and why do I get undefined?
I'm using node as a console.
You need to add a return statement to your outermost function, like this:
var every = function(arr, req){
return arr.map(function(item){
return req(item);
}).reduce(
function(total, num){
return total && num;
});
}
// This returns true
console.log(every([NaN, NaN, NaN], isNaN));
EDIT: Fixed return value, thanks @Kevin B
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.