【问题标题】:When would a function's actual .length be insufficient for _.curry()什么时候函数的实际 .length 不足以满足 _.curry()
【发布时间】:2018-02-07 20:36:10
【问题描述】:

我遇到了一个不稳定的情况,在 a 上使用 _.curry 的函数会立即调用该函数。在阅读了 lodash 文档之后,我们发现我们需要声明 arity,这要归功于编写得非常好的文档:

如果 func.length 不够,可以指定 func 的数量。

但是,我很好奇是否有人知道为什么会发生这种情况的任何实际示例(不一定是我的代码库中发生这种情况的具体原因)。

【问题讨论】:

  • AFAIK 不可能覆盖函数的长度。你为什么不向我们展示你的功能,希望有人能解释问题出在哪里?
  • 也许我应该问问 lodash 的维护者,因为他们似乎知道它不会“足够”的情况。
  • 我能想到很多这样的情况是不够的。你为什么不告诉我们你的具体情况?

标签: reactjs webpack lodash redux-thunk currying


【解决方案1】:

但是,我很好奇是否有人知道为什么会发生这种情况的任何实际示例(不一定是我的代码库中发生这种情况的具体原因)。

例子:

  • 该函数使用arguments 对象而不是形参:

function sum() {
  var total = 0;
  for (var i = 0; i < arguments.length; i += 1) {
    total += arguments[i];
  }
  return total;
}

console.log('length', sum.length);   // 0
console.log('result', sum(3, 4));
  • 该函数使用“rest”参数:

function sum(...values) {
  return values.reduce((a, v) => a + v, 0);
}

console.log('length', sum.length);    // 0
console.log('result', sum(3, 4));
  • 函数已被部分评估或经历了其他一些转换:

function add(x, y) { return x + y; }

var inc = _.partial(add, 1);

console.log('add length', add.length);        // 2
console.log('inc length', inc.length);        // 0
console.log('result', inc(8));

var squarePlusOne = _.flow(x => x * x, x => x + 1);

console.log('length', squarePlusOne.length);  // 0
console.log('result', squarePlusOne(7));
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"&gt;&lt;/script&gt;
  • 该函数的参数比您实际想要的要多(即它具有可选参数)

function combine(x, y, z) {
  return x + y + (z || 0);
}

console.log('length', combine.length);   // 3
console.log('result', combine(3, 4));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-25
    • 2016-01-04
    • 2020-05-12
    • 2021-09-03
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多