为什么每次迭代都会重置此代码中的'output'变量? [英] Why does the 'output' variable in this code get reset every iteration?
问题描述
大家好,我正在阅读一本JS书,其中一个挑战让我们在1到100之间循环所有整数,如果它可以被3整除则写Fizz,如果它可以被5整除则写Buzz和FizzBuzz如果它可以被两者整除,否则只记录数字。我设法解决了问题的代码,但我不确定为什么每次迭代都会重置'output'声明,而不是存储一长串的Fizzes和Buzzes。这是代码:
Hi guys, I'm reading a JS book at the moment and one of the challenges had us loop over all integers between 1 - 100 and write "Fizz" if it's divisible by 3, "Buzz" if it's divisible by 5 and "FizzBuzz" if it's divisible by both, otherwise just log the number. I managed to work out the code for the problem but I'm unsure as to why the 'output' declaration gets reset every iteration rather than storing a long line of Fizzes and Buzzes. Here's the code:
for (let num = 1; num <= 100; num++){
let output = "";
if(num % 3 == 0) output += "Fizz";
if(num % 5 == 0) output += "Buzz";
console.log(output || num);
}
我的尝试:
我试过谷歌搜索问题,但我找不到任何具体的变量为什么有时会重置每次迭代,而有时它会一遍又一遍地存储以连接所有内容。
What I have tried:
I've tried googling the question but I can't find anything specific as to why a variable sometimes resets each iteration, whereas sometimes it gets stored over and over to concatenate everything.
推荐答案
这是因为你在循环中声明它 。在循环外声明它以连接每次迭代:
It's because you declare it inside the loop. Declare it outside the loop to concatenate each iteration:
let output = "";
for (let num = 1; num <= 100; num++){
if(num % 3 == 0) output += "Fizz";
if(num % 5 == 0) output += "Buzz";
console.log(output || num);
}
这篇关于为什么每次迭代都会重置此代码中的'output'变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!