簡體   English   中英

創建一個 function,它創建 x 行和 y 列的“*”

[英]Create a function that creates x rows and y columns of “*”

output(在這種情況下)我想要的是三行“**”,因為行是 3,列是 2。

  function drawbox(row,column){
    for (var j=0;j<row;j++)
    {
    for (var i=0;i<column;i++)
    {   document.write("*");
        if (i=(column-1))
          {document.write("<br>")}

    }

    }              
  }

  drawbox(3,2);


</script>

簡單 - 只需使用兩個循環,但不要擔心if

 function drawBox(row, column) { for (let i = 0; i < row; i++) { for (let j = 0; j < column; j++) { document.write("*"); } document.write("<br>"); } } drawBox(3, 2);

ES6 和函數式編程的替代答案(因為我非常喜歡 FP):

function drawbox(rows, columns){
    const row = Array(columns).fill().map(() => '*').join('');
    const _rows = Array(rows).fill().map(() => row).join('<br/>');
    document.write(_rows);   
}

我們可以使用重復function

 <script> 


  function drawbox(row,column){
    for (var j=0;j<row;j++)
    {

     document.write("*".repeat(column));

     document.write("<br>")

    }              
  }

  drawbox(3,2);


</script>

我認為最簡單的方法:

function grid(row, col){
    document.write(Array(row).fill(Array(col).fill('*')).join('<br>'));
}

另請注意:您是 function 不起作用,因為您使用的是賦值運算符:

if (i=(column-1))

...當您應該使用相等比較運算符時:

if (i===(column-1))

我在早期學到的東西。 當您處理二維數據結構時,結構意義上的第二維通常是多余的。

以 2 維顯示數據也只需要 1 個循環,而不是 2 和 4,如其他解決方案所示。

const drawbox = (r, c) => {
  for (let ri = 1, i = 0;  i < r*c; ri++, i++) {
    document.write('*')
    if (ri >= r && i !== r*c) {
      document.write('<br>')
      ri = 0
    }
  }
}

您可以在帶有模塊運算符 -> if (i%r === 0)的 for 循環中僅使用i (不帶ri )來確定是否應插入換行符。

const drawbox = (r, c) => {
  for (let i = 1;  i < r*c+1; i ++) {
    document.write('*')
    if (i%r === 0 && i !== r*c) {
      document.write('<br>')
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM