[英]Node.js Pattern
var readline=require("readline-sync");
var n=parseInt(readline.question());
for (var i=1;i<=n;i++){
var str="";
for (var j=1;j<=i;j++){
str+="*";
console.log(str);
}console.log();
}
Plesse tell me where I am doing wrong.
请告诉我哪里做错了。 I want to print a pattern for
我想打印一个图案
*
**
***
****
*****
Also please tell me where I can do improvements.也请告诉我哪里可以改进。 Thanks !
谢谢 !
You need to know better about variable scopes.您需要更好地了解变量范围。
var
is hoisted to the module level that why str
is not defined on each iteration of your outer for
loop. var
被提升到模块级别,为什么str
没有在外部for
循环的每次迭代中定义。 See Closure见关闭
Just use let
instead of var
to define str
in a for
block scope.只需使用
let
而不是var
在for
块 scope 中定义str
。
for (var i=1;i<=n;i++){
let str="";
for (var j=1;j<=i;j++){
str+="*";
console.log(str);
}
console.log();
}
You are printing that string every time you append a * to string.每次您将 append a * 转换为字符串时,您都在打印该字符串。 and you can fix it using following
您可以使用以下方法修复它
n=5 for (var i=0;i<n;i++){ var str=""; for (var j=0;j<=i;j++){ str+="*"; } console.log(str); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.