JSHint显示错误:
“在循环内声明的引用外部作用域变量的函数可能会导致语义困惑”。
如何改进以下代码以消除警告?

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];
    }
};

最佳答案

您不应在循环体内使用函数表达式,而应在外部进行声明:

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];
    }
}

当然,只需使用 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];
}

最后,Object.keys(…).includes(…)可以简化为operator in operators[key]

关于javascript - JSHint警告 "Function declared within loop referencing an outer scope variable may lead to confusing semantics"。如何改善代码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48442078/

10-12 16:21