尝试在chrome中用javaScript打印一个简单的三角形但相似的项目被分组为一个

问题描述 投票:0回答:2

我是 Javascript 新手,目前正在学习如何借助 for 和 while 循环在控制台中打印消息。

我只是想打印从一个简单的三角形开始的图案,我为此编写了以下程序。

for (let i = 1; i <= 5; i =i+1)
     {
       for(let j=0;j<=i; j=j+1)
         {
           console.log("#");
         }
     }

这是我当前需要的输出。

   # 

   ## 

   ### 

   #### 

   ##### ```


But when the script runs the browser groups similar items as 1

The console shows output like this :

    `21 #`

Tried unchecking the group similar items in the settings and also turned on the timestamps but not able get the pattern. Please guide me on this. Thanks

[enter image description here](https://i.stack.imgur.com/vIimw.png)
[enter image description here](https://i.stack.imgur.com/uoBOp.png)
[enter image description here](https://i.stack.imgur.com/Bh6YT.png)
javascript console pattern-matching
2个回答
0
投票

您遇到的问题是由于

console.log
函数在 JavaScript 中的工作方式造成的。每次调用
console.log
都会在控制台中输出一个新行,这就是为什么您会在单独的行上看到每个
#
。要创建您想要的图案,您需要为三角形的每一行构建一个字符串,然后打印该字符串。您可以通过以下方式修改代码来实现此目的:

for (let i = 1; i <= 5; i++) {
    let row = '';
    for (let j = 0; j < i; j++) {
        row += '#';
    }
    console.log(row);
}

在代码的此修订版本中,内部循环 (

for (let j = 0; j < i; j++)
) 通过连接
row
字符构造字符串
#
。添加到
#
row
字符数由外循环中
i
的当前值确定。内部循环完成
i
的每次迭代后,
row
字符串(现在包含
i
#
个字符)被打印到控制台。

这将产生输出:

#
##
###
####
#####

每一行对应于外循环的一次迭代,内循环确定每行中有多少个

#
字符。这种方法可确保整个图案在控制台中正确打印。


0
投票

console.log() 每次调用时都会在控制台上打印一个新条目。对于你想做的事情,你应该尝试这个:

for (let i = 1; i <= 5; i =i+1)   
{
  console.log("#".repeat(i));
}
     

© www.soinside.com 2019 - 2024. All rights reserved.