[英]JSHint warning "Function declared within loop referencing an outer scope variable may lead to confusing semantics" . How can I improve the code?
JSHint shows the error: "Function declared within loop referencing an outer scope variable may lead to confusing semantics". JSHint 显示错误:“在循环内声明的函数引用外部 scope 变量可能会导致语义混淆”。 How can I improve the following code to get rid of the warning?
如何改进以下代码以消除警告?
var getPrecedence = function getPrecedence(operator, operators) {
var keys = Object.keys(Object(operators));
for (var i = 0, len = keys.length; i < len; i++) {
var check = Object.keys(operators[keys[i]]).some(function (item) {
return item === operator;
});
if (check) return operators[keys[i]][operator];
}
};
You are supposed not to use the function expression inside the loop body, but instead declare it outside: 你不应该在循环体内使用函数表达式,而是在外面声明它:
function getPrecedence(operator, operators) {
function isOperator(item) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
return item === operator;
}
var keys = Object.keys(Object(operators));
for (var i = 0, len = keys.length; i < len; i++) {
var check = Object.keys(operators[keys[i]]).some(isOperator);
// ^^^^^^^^^^
if (check) return operators[keys[i]][operator];
}
}
Of course the whole thing could be simplified by just using includes
instead of some
, and find
instead of the loop: 当然,通过使用
includes
而不是some
,可以简化整个事情,并find
而不是循环:
function getPrecedence(operator, operators) {
var keys = Object.keys(Object(operators));
var opkey = keys.find(key =>
Object.keys(operators[key]).includes(operator)
);
if (opkey) return operators[opkey][operator];
}
And finally, Object.keys(…).includes(…)
can be simplified to operator in operators[key]
. 最后,
Object.keys(…).includes(…)
可以简化为operator in operators[key]
。
Add it before calling the function, this one will bypass that check在调用 function 之前添加它,这个将绕过该检查
/* jshint -W083 */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.