FizzBu​​zz for Javascript:console.log如何知道何时打印一个或另一个变量?

时间:2018-05-22 23:04:17

标签: javascript logic fizzbuzz

我正在看这段代码:

for (let n = 1; n <=100; n++) {
  let output = "";
  if (n % 3 == 0) output += "Fizz";
  if (n % 5 == 0) output += "Buzz";
console.log(output || n);
}

控制台如何决定何时打印数字或单词?

1 个答案:

答案 0 :(得分:6)

""是一个假值,因此在执行"" || 1时,它将被视为false || 1,它将打印1

您可以在https://developer.mozilla.org/en-US/docs/Glossary/Falsy

了解更多信息

逻辑OR运算符有效,因为在Javascript中,如果 truthy ,则返回第一个表达式,否则返回第二个表达式。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical

了解详情