【问题标题】:Blank Local Variable Declaration - JS空白局部变量声明 - JS
【发布时间】:2021-06-03 16:27:07
【问题描述】:

我在下面有完全相同的代码,除了顶部来自 HeadFirst JS 书,他们将输出声明为空白变量,然后为其分配一个字符串。其次是我乱七八糟地看到代码仍然可以工作,而无需先将输出声明为空白变量。声明输出有什么用;空白 vs 跳过那部分。

const printAndGetHighScore = function (score) {
    let highscore = 0;
    let output;
    for (i = 0; i < scores.length; i++) {
        output = `Bubble solution #${i} score: ${scores[i]}`;
        console.log(output);
        if (scores[i] > highscore){
            highscore = scores[i]
        }
    }
    return highscore;
};
const printAndGetHighScore = function (scores) {
    let highscore = 0
    for (let i = 0; i < scores.length; i++) {
        let output = `Bubble Solution #${i} score: ${scores[i]}`
        if(scores[i] > highscore){
            highscore = scores[i]
        }
    }
    return highscore;
}
console.log(`Bubbles test: ${scores.length}`);
console.log(`Highest bubble score ${printAndGetHighScore(scores)}`)

【问题讨论】:

  • 第二个示例中是否应该像第一个示例一样包含console.log(output);
  • 您的第一个循环缺少let i 声明

标签: javascript function variables scope


【解决方案1】:

在这种情况下,没有区别。由于output 仅被引用一次,并且它在output 被分配到之后立即在循环内同步完成,因此从使代码工作的角度来看,声明变量的位置并不重要。

甚至可以在外面声明output,或者在外面声明highscore

let output;
let highscore;
const printAndGetHighScore = function (score) {
    highscore = 0;
    for (i = 0; i < scores.length; i++) {
        output = `Bubble solution #${i} score: ${scores[i]}`;
        console.log(output);
        if (scores[i] > highscore){
            highscore = scores[i]
        }
    }
    return highscore;
};

这也可以。

如果变量在稍后可引用,例如在函数中,则在循环外而不是循环内声明变量将不起作用:

const fns = [];
let i = 0;
for (; i < 3; i++) {
  fns.push(() => console.log(i));
}
for (const fn of fns) fn();

在上面的例子中,由于只为i创建了一个绑定,所以创建的函数都引用了那个i,循环结束后为3。在循环内声明一个变量将允许所有函数具有单独的绑定:

const fns = [];
for (let i = 0; i < 3; i++) {
  const inner = i; // not strictly necesary, but makes the scoping easier to understand
  fns.push(() => console.log(inner));
}
for (const fn of fns) fn();

但还有另一个原因更喜欢在循环内(如您的第二个示例)而不是外部声明变量:代码可维护性The narrower a scope a variable has, the easier it is to reason about it and the code around it.

【讨论】:

  • 当一个答案解决了您的问题时,您可以考虑将其标记为已接受(选中左侧的复选标记)以表明问题已解决:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 2023-03-24
相关资源
最近更新 更多