javascript - javascript code raising warning in jshint.com "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics"
问题描述
The javascript code:
for (j = 0; j < array.length; j ++) {
if (
array[j].some(
function(word) {
return word.indexOf(array1[i]) > -1;
}
)
) {
makeSomething();
}
}
produces a Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (array1)
warning in jshint.com
.
Actually it works.
Is it really problematic?
How should it be written?
解决方案
不,这不是问题。警告缺少推理:
如果回调将被异步回调,那么它会令人困惑:
for(i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i); // guess what this logs
});
}
但是你真的应该总是声明变量并总是使用let
or const
:
for (let j = 0; j < array.length; j ++) {
这将使警告消失,并且还将修复上面的示例(并且它避免了可能令人困惑的隐式 global)。
推荐阅读
- c - 从nodemcu lua中的lua函数返回大字符串
- python - 从元组列表转换后,python字典中的排序顺序丢失
- python - 如何在同一标签下绘制整个 Pandas DataFrame?
- python-3.x - 如何有效地使用 Django 查询和 Q 过滤查询集中的每个对象并为查询集中的每个唯一字段返回 1 个字段值
- ruby - 如何防止 peek 方法将读取光标向前移动?
- html-table - 表内的 Bootstrap 4 datetimepicker 设计不正确
- python - Pandas 使用多个条件在列中分配值:
- java - 使用 java nullpointerexception 显示背景图像
- mysql - 在 bash 中获取 MySQL 输出
- django-rest-framework - 脚本的哪一部分使 JSON API 作为 Django Rest Framework 中的对象数组返回?