亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在javascript中打印數字序列

在javascript中打印數字序列

牧羊人nacy 2023-10-14 18:23:44
我確信這是一個非常簡單的編程問題,但是我似乎無法理解它......我試圖讓 console.log 打印出這樣的數字 - 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 - 每行一個。我認為可以使用模來實現這一點,但是,我似乎不知道如何使用它。這是代碼:iteration = 16;for (var i = 0; i < iteration; i++) {    if(i == iteration%4 )    console.log(i);}
查看完整描述

2 回答

?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

是的,您需要一個循環。

不,您不需要余數運算符%。這會給你

0?1?2?3?0?1?2?3?...

但您可以將實際值除以4并取整數值console.log

const iteration = 16;


for (let i = 0; i < iteration; i++) {

? ? console.log(Math.floor(i / 4) + 1); // offset for starting with 1

}


查看完整回答
反對 回復 2023-10-14
?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

我建議您使用兩個嵌套的 for 循環,一個用于行,另一個用于列。


這是我將如何做的一個例子:


const columns = 4;

const rows = 4;


//if you want to just console.log each number on a different line

for (let i = 1; i <= rows; i++) {

  for (let j = 1; j <= columns; j++) {

    console.log(i);

  }

  console.log("\n");

}


//if you want to add each number to an array, and then log the array

for (let i = 1; i <= rows; i++) {

  let columnsArray = [];

  columnsArray.length = columns;

  columnsArray.fill(i);

  console.log(columnsArray);

}


//if you want to just log the numbers, you can spread the array

for (let i = 1; i <= rows; i++) {

  let columnsArray = [];

  columnsArray.length = columns;

  columnsArray.fill(i);

  console.log(...columnsArray);

}


//or you could push the arrays in another one, and get a matrix!

const matrix = [];

for (let i = 1; i <= rows; i++) {

  let columnsArray = [];

  columnsArray.length = columns;

  columnsArray.fill(i);

  matrix.push(columnsArray);

}

console.log(matrix);


不清楚你想要的輸出,所以我有點偏離主題,并為我想到的不同情況做了一個例子。


查看完整回答
反對 回復 2023-10-14
  • 2 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號