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

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

如何制作水平打印的for循環

如何制作水平打印的for循環

一只斗牛犬 2023-07-06 14:48:04
我想要一個打印 5 個垂直打印的隨機數的循環到目前為止我已經...for(let i = 0; i < 5; i++ ) {let x = Math.floor(Math.random() * 10);console.log(x)}然后當我運行它時,我得到了 5 個隨機數,但我只是不知道如何水平打印它
查看完整描述

4 回答

?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

通過水平打印,我假設您的意思是在同一行中。在這種情況下,您可以執行上面提到的操作,或者您可以創建一個包含所有數字的字符串


let string = "";

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

   let x = Math.floor(Math.random() * 10);

   string = `${string} ${x.toString()}`;

}

console.log(string);


查看完整回答
反對 回復 2023-07-06
?
手掌心

TA貢獻1942條經驗 獲得超3個贊

您可以將它們全部添加到一個大字符串中并在最后打??!


output = ''

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

    let x = Math.floor(Math.random() * 10);

    output = output + ' ' + x;

}

console.log(output);


查看完整回答
反對 回復 2023-07-06
?
慕尼黑的夜晚無繁華

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

你可以這樣做。


var values=[];

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

   values.push(Math.floor(Math.random() * 10));

}

console.log(values);    //if you want to print an array

console.log(values.join()); //if you want to print as string with coma sepration

console.log(values.join(" ")); //if you want to print as string with empty spaces


查看完整回答
反對 回復 2023-07-06
?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

取決于您想要的輸出格式,但您可以執行以下操作:


let arr = [];

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

  let x = Math.floor(Math.random() * 10);

  arr.push(x)

  console.log(x)

}

console.log(...arr)


如果你想用逗號來實現,你可以用 .map() 來實現。


let arr = [];

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

  let x = Math.floor(Math.random() * 10);

  arr.push(x);

  console.log(x);

}

const len = arr.length;

const commaArray = arr.map((x, i) => i < len - 1 ? x + ',' : x);

console.log(...commaArray);


查看完整回答
反對 回復 2023-07-06
  • 4 回答
  • 0 關注
  • 178 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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