【问题标题】:How to generate numbers upto n using a loop? [closed]如何使用循环生成最多 n 的数字? [关闭]
【发布时间】:2020-10-24 06:17:39
【问题描述】:

实际上我在这里尝试生成这样的数字。 1.0 1.1 ... 1.9 2.0 2.1 ... 2.9 到 N。有人可以指导我如何使用循环生成该格式的数字。

【问题讨论】:

  • 不确定你在问什么,但[...Array(n * 10)].map((_, i) => i / 10)?
  • @mplungjan 感谢您的回复。实际上,我在这里尝试以上述格式生成数字。在索引的基础上。
  • @mplungjan 其实我只想在地图中生成数字。
  • ((index+10)/10).toFixed(1)
  • @Kanekar 我将评论转换为答案并添加了循环版本

标签: javascript ecmascript-6


【解决方案1】:

注意返回的数组是字符串,因为 JS 会在小数点后去掉零

单行无循环

const genFloats = n => [...Array(n+10)] // generate array
  .map((_, i) => (i / 10).toFixed(1))   // process the indicii of the array
  .slice(10); // drop the first 10


console.log(genFloats(20))

循环:

const genFloats = n => { 
  const res = [];
  for (let i=10;i<=n*10;i++) {
    console.log(i,i/10)
    res.push((i/10).toFixed(1)); 
  }  
  return res
};
console.log(genFloats(5))

【讨论】:

  • mplungjan 我接受您的回答,但您能否在地图或 for 循环中打印这些数字,如果可以的话,我会更容易理解。因为我是编程新手。提前致谢。
  • 我不明白你的意思。如果需要for (....) { console.log(i,i/10); res.push(...);},可以添加大括号和控制台日志
  • 没关系,我会这样做,我想说的是,当您在地图外打印 console.log 时,我想在地图功能内打印该 console.log,而不是在您打印的外面。无论如何,非常感谢您在这里付出宝贵的时间。 :)
【解决方案2】:

使用((index+10)/10).toFixed(1)

const arr = Array.from({length:20},(_,i) => ({a:`Item #${i+1}`}))

const res = arr.map((o,i) => ({...o, num:((i+10)/10).toFixed(1)}))

console.log(res)
.as-console-wrapper {max-height: 100%!important;top:0}

【讨论】:

  • 感谢您的回答并抽出宝贵时间。
猜你喜欢
  • 2020-12-06
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-01-29
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多