javascript - 高阶函数返回非 boolean 值以外的任何内容都是有问题的。为什么?

标签 javascript boolean higher-order-functions

function each(collection, callback) {
  var arr = [];
  for(var i = 0; i < collection.length; i++) {
      var result = callback(collection[i])
      if (typeof result !== 'undefined') {
        arr.push(callback(collection[i]));
      }
    }
  return arr
}

function isNumber(item) {
    if (typeof item === "number") {
      return item * 2;
    }
}

我正在尝试理解高阶函数。上面的方法有效,但显然不是使用 isNumber 返回值的最佳实践。有人告诉我应该返回 boolean 值。为什么?它有效。

更新: 看来是因为函数名的原因!谢谢大家,我只是觉得可能有一些技术原因

最佳答案

如果调用函数isNumber,它应该返回一个 boolean 值。

此外,您的 every 函数是一个 map 而不是 each。在这种情况下,您的代码可能应该如下所示。

function flatMap(collection, callback) {
  var arr = [];
  for(var i = 0; i < collection.length; i++) {
      var result = callback(collection[i])
      if (typeof result !== 'undefined') {
        arr.push(callback(collection[i]));
      }
    }
  return arr;
}

function times2(item) {
    if (typeof item === "number") {
      return item * 2;
    }
    return item;
}

map([1,2,3,"hello"], times2);

如果你想要可以停止的迭代,那么它看起来像

function iterate(collection, callback) {
  for(var i = 0; i < collection.length; i++) {
    var result = callback(collection[i])
    if (typeof result === false) {
      return;
    }
  }
}

function doSomethingAndStopIfNotANumber(item) {
   console.log(item);
   return typeof item == "number";
}

iterate([1,2,3, "hello", 4, 5], doSomethingAndStopIfNotANumber);

请注意Array.prototype.forEach不允许您通过返回 false 来停止迭代,因为您需要滥用 Array.prototype.every (因为该函数返回一个 boolean 值,所以这只是一个语义问题,不像映射那样构建一个数组并将其丢弃)或像我上面那样编写一个函数。

关于javascript - 高阶函数返回非 boolean 值以外的任何内容都是有问题的。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37861822/

相关文章:

Python 'while' 有两个条件 : "and" or "or"

ios - 访问在几个不同的可能类中设置的 BOOL 标志

javascript - 使用高阶函数的 N*N 大小的单位矩阵

unit-testing - 如何在 Clojure 中测试高阶函数?

javascript - jQuery AJAX 200 状态,但神秘的语法错误

Javascript:在历史对象中的ff中自定义函数消失

javascript - 如何使用SystemWorker执行PowerShell命令?

javascript - 在 kendo.ui.GridColumn 中格式化日期和 boolean 值

PHP数组函数,返回给定键的子集

javascript - CSS - 在输入字段的左侧对齐标签