gpt4 book ai didi

JavaScript 代码在 jshint.com 中引发警告 "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics"

转载 作者:行者123 更新时间:2023-12-01 01:02:59 30 4
gpt4 key购买 nike

JavaScript 代码:

for (j = 0; j < array.length; j ++) {
if (
array[j].some(
function(word) {
return word.indexOf(array1[i]) > -1;
}
)
) {
makeSomething();
}
}

产生一个在引用外部作用域变量的循环内声明的函数可能会导致语义困惑。 jshint.com 中的 (array1) 警告。

实际上它有效。

真的有问题吗?

应该怎么写?

最佳答案

不,这不是问题。该警告缺少推理:

如果回调是异步回调的,那么就会很困惑:

   for(i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i); // guess what this logs
});
}

但是您确实应该始终声明变量,并且始终使用 letconst :

>
  for (let j = 0; j < array.length; j ++) {

这将使警告消失,并且还将修复上面的示例(并且它避免 probably confusing implicit global )。

关于JavaScript 代码在 jshint.com 中引发警告 "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55894175/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com