[英]Why does my boolean return 'undefined'?
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. 我正在通过Eloquent Javascript进行工作,这里有一个练习来制作
every
函数,该函数接受一个数组和一个函数,并根据通过该函数后数组中所有项目返回的内容返回true或false。
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
. 我很困惑,因为当我在函数内执行console.log()时,会两次获得布尔值...但是当我进行console.log(every(arr,func))时,会得到
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? 那么,为什么在函数内部两次都
true
,为什么我未定义?
I'm using node as a console. 我正在使用节点作为控制台。
You need to add a return statement to your outermost function, like this: 您需要向最外层函数添加return语句,如下所示:
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 编辑:固定的返回值,谢谢@凯文B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.