【问题标题】:Unexpected assignment within a 'do...while' statement. Why is this bad practice and what can I do instead?'do...while' 语句中的意外分配。为什么这是不好的做法,我能做些什么呢?
【发布时间】:2018-09-20 06:35:15
【问题描述】:

我收到一个 eslint 错误: [eslint] 'do...while' 语句中的意外分配。 (无条件分配)

为什么会这样? 我能做些什么来修复它? 为什么我不允许这样做?为什么这是不好的做法?

window.smoothScroll = function (target) {
    let scrollContainer = target;
    do {
        scrollContainer = scrollContainer.parentNode;
        if (!scrollContainer) return;
        scrollContainer.scrollTop += 1;
    } while (scrollContainer.scrollTop === 0);

    let targetY = 0;
    do {
        if (target === scrollContainer) break;
        targetY += target.offsetTop;
    } while (target = target.offsetParent);

    const scroll = (c, a, b, i) => {
        i += 1; if (i > 30) return;
        c.scrollTop = (((a + (b - a)) / 30) * i);
        setTimeout(() => { scroll(c, a, b, i); }, 10);
    };
    scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0);
};

【问题讨论】:

    标签: javascript ecmascript-6 eslint


    【解决方案1】:

    while 需要一个表达式,而target = target.offsetParent 是一个赋值。虽然赋值确实评估一个表达式,但经常它的使用要么是错误,要么是代码异味。例如,正如 linter 解释的那样:

    if (user.jobTitle = "manager") {
    

    上面的代码几乎可以肯定是一个错字。如果你想给一个变量赋值,最好在一个独立的行上做,而不是在一个表达式中,让你的代码对未来的读者(包括你自己)更清楚。

    在您的代码中,您可以通过在do 底部分配target 来修复它,然后将target 放入while 条件中:

    do {
      if (target === scrollContainer) break;
      targetY += target.offsetTop;
      target = target.offsetParent
    } while (target);
    

    【讨论】:

    • 可能值得注意有时您可以在while 中使用赋值作为速记。例如,您对下一个零感兴趣,而忽略其他输入 while (myVar = someIntegerGenerator.next()) 作为 do...while 您可以处理所有非零输出并在达到零时停止。然而,根据我的经验,这种结构很少需要。如果您浏览它也可能会感到困惑 - 它通常伴随着注释 - 在自文档代码的风格中,您可以将作业拉到正文中。
    猜你喜欢
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 2015-06-21
    • 2019-03-21
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多