高阶函数返回非布尔值以外的任何东西都是有问题的。为什么?

Higher order functions returning anything but a non-boolean is questionable. Why?

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;
    }
}

我正在尝试了解高阶函数。上面的方法有效,但显然不是 return 具有 isNumber 的值的最佳实践。有人告诉我布尔值应该是 returned。为什么?有效。

更新: 好像是函数名的问题!谢谢大家我只是认为可能是一些技术原因

如果一个函数被调用 isNumber,它应该 return 一个布尔值。

此外,您的每个函数都是 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 does not allow you to stop iteration by returning false, for that you'd need to misuse Array.prototype.every(因为那个函数 return 是一个布尔值,所以它只是一个语义问题,不像 map 你建立一个数组然后把它扔掉)或者像我这样写一个函数上面做了。