【问题标题】:Why the output of console.log and document.write are different?为什么 console.log 和 document.write 的输出不一样?
【发布时间】:2018-03-24 03:12:45
【问题描述】:

我尝试编写一个简单的代码以在 JavaScript 中打印斐波那契数列。首先我尝试使用“console.log()”。它给出了错误的输出。我尝试更改变量及其值。但我无法获得正确的输出。然后我检查了谷歌。我发现我的代码的每一行都是正确的,除了'console.log()'。他们使用'document.write()'而不是'console.log'。你能解释一下为什么'console.log ()' 和 'document.write()' 在以下程序中给出不同的输出:

<script>
   let a=0;
   let b=1;
   let c=0;
  for(let i=0;i<=10;i++)
   {
       document.write(a +'</br>');
       console.log(a);
       c=a+b;
       a=b;
       b=c;
   }    
</script>

document.write() 的输出:0,1,1,2,3,5,8,13,21,34,55

console.log() 的输出:0,1,2,3,5,8,13,21,34,55

【问题讨论】:

    标签: fibonacci


    【解决方案1】:

    您可能会看到控制台输出正在“堆叠”。例如,在 Chrome DevTools 中,如果相同的输出连续多次记录到控制台,而不是在多行上打印,它只是在 single 行的左侧显示一个小圆圈,指示如何多次出现该输出。在您的具体示例中,我希望在控制台输出中的 1 左侧看到一个小的 2

    请参阅Benjamin W.this answer 以获取更多信息的链接,包括如何关闭此功能。

    另外,请注意您的自闭合标签。代码示例中的换行符应显示为:&lt;br /&gt;,如 the Mozilla web docs. 所述

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 2018-06-09
      • 1970-01-01
      • 2021-07-21
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多