JSHint警告"在循环中声明的函数引用外部范围变量可能会导致语义混乱" 。我该如何改进代码?

时间:2018-01-25 11:44:48

标签: javascript loops closures jshint

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

I  2018-01-25 11:35:23 +0000 [error]: Exception emitting record: No such file or directory @ sys_fail2 - (/var/log/fluentd-buffers/kubernetes.system.buffer..b5638802e3e04e72f.log, /var/log/fluentd-buffers/kubernetes.system.buffer..q5638802e3e04e72f.log)

I  2018-01-25 11:35:23 +0000 [warn]: emit transaction failed: error_class=Errno::ENOENT error="No such file or directory @ sys_fail2 - (/var/log/fluentd-buffers/kubernetes.system.buffer..b5638802e3e04e72f.log, /var/log/fluentd-buffers/kubernetes.system.buffer..q5638802e3e04e72f.log)" tag="docker"

I    2018-01-25 11:35:23 +0000 [warn]: suppressed same stacktrace

1 个答案:

答案 0 :(得分:4)

你不应该在循环体内使用函数表达式,而是在外面声明它:

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代替somefind代替循环,就可以简化整个过程:

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]