【问题标题】:jshint - Don't make functions within a loop using Array.findjshint - 不要使用 Array.find 在循环中创建函数
【发布时间】:2017-05-03 17:56:46
【问题描述】:

我知道这个问题已经存在了一段时间,但我还没有找到可以解决我的问题的答案(抱歉,如果我遗漏了任何问题)。

无论如何,我有以下代码:

for(let i=0; i<array.length; i++) {
    let value = array[i];
    let anotherValue = anotherArray.find(val => val.key === value.key);
}

该代码使 jshint 抛出警告:不要在循环中创建函数。 (W083)

我需要访问“for”范围内的变量这一事实使我需要在其中声明一个函数。

我尝试了以下方法:

let myFunc = (val) => {
    //no value here to compare
}
for(let i=0; i<array.length; i++) {
    let value = array[i];
    let anotherValue = anotherArray.find(myFunc);
}

如果我在 for 之外声明它,我将无法访问 value 变量。

【问题讨论】:

  • 只需关闭该警告消息。
  • 问题根本不在于消息。那很容易摆脱。我只是认为它必须是一个更好的实现。
  • 你的实现绝对没问题。

标签: javascript jshint


【解决方案1】:

尝试使用Array.forEach 而不是for-loop:

array.forEach((value) => {
  let anotherValue = anotherArray.find(val => val.key === value.key);
  /* do anything with anotherValue */
}

或者,您可以curry your function 以便能够使用value 并且仍然具有功能:

let myFunc = candidate => target => candidate.key === target.key;
for (let i = 0; i < array.length; i++) {
    let anotherValue = anotherArray.find(myFunc(array[i]));
}

另外,您可以通过在文件顶部添加指令来告诉 JSHint 忽略此文件中的此规则:

/* jshint loopfunc: true */

【讨论】:

  • curry 方法还在循环的每次迭代中生成一个函数。
  • 确实如此,我只是认为 jshint 不会抱怨它,因为“函数生成器”是在循环之外定义的。不过,我还没有测试过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2012-10-05
  • 2013-03-17
相关资源
最近更新 更多