[英]I want to print a square using the hash characters, javascript
I am trying to print a square using the hash character我正在尝试使用 hash 字符打印正方形
function square(num){
for(i = 0; i < num; i++){
for(j = 0; j < num; j++){
console.log("#");
}
console.log(" ");
}
}square(2);
/* my output is: "#" "#" /* 我的 output 是:“#”“#”
"#" "#" "#" "#"
instead of: "##" "##" */代替: ”##” ”##” */
Every time you console.log()
, the console will print a new line.每次你
console.log()
时,控制台都会打印一个新行。 You need to add each row to one line like this:您需要将每一行添加到一行,如下所示:
function square(num){ for(i = 0; i < num; i++){ let row = '' for(j = 0; j < num; j++){ row+='#' } console.log(row+" "); } } square(4);
Creating a function named square to return a square pattern.Using squareArray as the solution array and result string to store the value for each inner loop.Finally, using join to convert array to string.创建一个名为 square 的 function 以返回一个正方形模式。使用 squareArray 作为解决方案数组和结果字符串来存储每个内部循环的值。最后,使用 join 将数组转换为字符串。
function square(num) { const squareArray = []; let result; for (let i = 0; i < num; i++) { result = ""; for (let j = 0; j < num; j++) { result += "#"; } squareArray.push(result); } return squareArray.join("\n"); } console.log(square(2)); console.log(square(4)); console.log(square(6));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.