【问题标题】:Why does my boolean return 'undefined'?为什么我的布尔值返回“未定义”?
【发布时间】:2015-12-16 03:32:27
【问题描述】:

我正在使用 Eloquent Javascript,并且有一个练习来制作一个 every 函数,该函数接受一个数组和一个函数,并根据数组中的所有项目在通过函数后返回的内容返回 true 或 false。

我很困惑,因为当我在函数中执行 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));

那么为什么我的函数中会出现两次true,为什么会出现未定义?

我使用节点作为控制台。

【问题讨论】:

  • 你从来没有从every返回任何东西,所以console.log(every(...))永远是未定义的。
  • 除了缺少的return,你真的应该只使用arr.every(req),如果你选择reduce,你应该总是传递一个初始累加器值以覆盖空数组。

标签: javascript node.js boolean logical-operators reduce


【解决方案1】:

您需要在最外层的函数中添加一个 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));

编辑:固定返回值,感谢@Kevin B

【讨论】:

  • @KevinB 绝对是,我的错。
猜你喜欢
  • 2012-04-28
  • 2019-07-23
  • 1970-01-01
  • 2013-09-02
  • 1970-01-01
  • 2020-03-21
  • 2017-08-27
  • 2013-06-21
  • 1970-01-01
相关资源
最近更新 更多