简体   繁体   English

JS - 没有for或while循环重复动作N次?

[英]JS - repeat action N times without a for or while loop?

For example, I want to create some debug data array and I need a function that will take only the length of desired array and return array of objects with few props with random data values. 例如,我想创建一些调试数据数组,我需要一个只需要所需数组长度的函数,并返回几个具有随机数据值的道具的对象数组。

Is there a way to make this function without a for loop? 有没有办法在没有for循环的情况下完成这个功能? The reason for the question is that I have this i variable that I don't really need. 究其原因,问题是,我有这个i变,我并不真正需要的。

const generateData = (count) => {
  let data = []
  for (let i = 0; i < count; i++)  
    data.push({
      foo: Math.round(Math.random() * 100),
      bar: Math.random() > 0.5
    })
  return data  

}

You can create the array all at once with Array.from , if you want, no declaration or usage of any intermediate variable names: 你可以使用Array.from一次创建数组,如果你愿意,不要声明或使用任何中间变量名:

 const generateData = length => ( Array.from( { length }, () => ({ foo: Math.round(Math.random() * 100), bar: Math.random() > 0.5 }) ) ); console.log(generateData(5)); 

Instead of pushing every iteration into a target array you can create at once the array of size you need and then map each item to a random initiated value the way you need. 您可以立即创建所需大小的数组,然后将每个项目映射到您需要的随机启动值,而不是将每个迭代推送到目标数组中。

  function initArray(amount) { return [...new Array(amount)].map(() => ({ foo: Math.round(Math.random() * 100), bar: Math.random() > 0.5 })); } console.log(initArray(5)); 

Actually this is still an iterating but with more functional approach. 实际上,这仍然是一个迭代但具有更多功能的方法。

You can generate an array of n length and map() it to random objects. 您可以生成一个n长度的数组,并将它map()到随机对象。

 const createRandomArray = n => arr = [...Array(n)].map(() => ({ foo: Math.round(Math.random() * 100), bar: Math.random() > 0.5 })); console.log(createRandomArray(3)); 

You could make a recursive function: 你可以做一个递归函数:

const generateData = (count) => {
  let data = []
  function recursive(num) {
    if (num > 1) {
      num--;
      data.push({
        foo: Math.round(Math.random() * 100),
        bar: Math.random() > 0.5
      })
      recursive(num);
    }
    else {
      data.push({
        foo: Math.round(Math.random() * 100),
        bar: Math.random() > 0.5
      })
      return;
    }
  }
  recursive(count);
  return data  

}

Relatively large, but extremely simple to see what everything's doing. 相对较大,但看到一切正在做什么都非常简单。

 var timer = null; const generateData = (count,cb) => { let data = []; var num = 0; timer = setInterval(function(){ if(num>=count){ clearInterval(timer); cb(data) }else{ data.push({ foo: Math.round(Math.random() * 100), bar: Math.random() > 0.5 }) num++; } },10) } generateData(5,function(data){ console.log(data) }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM