[英]While loop with nested .forEach() produces no-loop-func es-lint warning
This is a javascript question.这是一个 javascript 问题。 I learned a sorting pattern in a Ruby tutorial a little while ago, now I'm trying to reuse the same pattern in javascript:
不久前,我在 Ruby 教程中学习了一种排序模式,现在我尝试在 javascript 中重用相同的模式:
const sortMyArray = (someArr) => {
let arrToSort = [...someArr];
let sorted = false;
while(!sorted) {
sorted = true;
array1.forEach((foo) => {
array2.forEach((bar, i) => {
if (foo.attr !== bar.attr) {
let plucked = arrayToSort.splice(i, 1)
arrayToSort.push(plucked[0])
sorted = false
}
})
})
}
}
I'm comfortable with this pattern and would like to keep it.我对这种模式感到满意,并希望保留它。 I've had to configure es-lint to ignore
no-loop-func
at the top of the file (the offending variable is the sorted
variable being passed from outside of the inner loop), but I'd like to avoid doing this with javascript as the warning is useful, I just don't think it helps with this example.我不得不将 es-lint 配置为忽略文件顶部的
no-loop-func
(有问题的变量是从内部循环外部传递的sorted
变量),但我想避免这样做javascript 作为警告很有用,我只是认为它对这个例子没有帮助。
Is there any other way to achieve this same sort that plays nicely in javascript?有没有其他方法可以在 javascript 中很好地实现这种相同的效果?
https://eslint.org/docs/rules/no-loop-func https://eslint.org/docs/rules/no-loop-func
The warning should be more specific that it's about the sorted
variable:警告应该更具体地说明它与
sorted
变量有关:
Function declared in a loop contains unsafe references to variable(s) 'sorted'.
在循环中声明的 Function 包含对“已排序”变量的不安全引用。 (no-loop-func)
(无循环功能)
What is doesn't like here is that there's a function inside a loop that modifies sorted
, which is outside--it's not aware that this function is guaranteed to only run only once within your while loop.这里不喜欢的是,在修改
sorted
的循环内有一个 function ,这是在外面 - 它不知道这个 function 保证只在您的 while 循环内运行一次。
Anyway, you can resolve this by instead using:无论如何,您可以通过以下方式解决此问题:
for (const foo of array1) {
or if you need the index (such as for the second loop):或者如果您需要索引(例如第二个循环):
for (let i = 0; i < array2.length; i++) {
const bar = array2[i];
Now you are no longer creating a function inside a loop that uses an external variable.现在,您不再在使用外部变量的循环内创建 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.