为了账号安全,请及时绑定邮箱和手机立即绑定

如何制作水平打印的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 关注
  • 112 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信