首页 > 解决方案 > 使用javascript生成具有特定时间范围的随机模拟数据

问题描述

我想生成具有以下结构的模拟数据。

条件,

开始时间和结束时间间隔应为 30 分钟或 1 小时。

同一天以不同的时间间隔进行 2-3 次模拟

  [{
    Id: 1,
    Subject: 'Bob',
    StartTime: new Date(2020, 6, 11, 9, 30),
    EndTime: new Date(2020, 6, 11, 11, 0),
    CategoryColor: '#1aaa55'
  }]

下面是我为生成模拟数据而编写的代码,

但我不确定如何生成数据逻辑。请帮忙

function random() {
  for (let index = 0; index <= 100; index++) {
    let x = {
      Id: getRandomInt(1, 1000),
      Subject: generateName(),
      StartTime: new Date(2020, 6, 11, 9, 30),
      EndTime: new Date(2020, 6, 11, 11, 0),
      CategoryColor: getRandomColor()
    }
    data.push(x);
  }
}

标签: javascriptarraystypescriptfor-loopobject

解决方案


您可以将用于随机名称生成器。对于随机数生成器,您可以Math.random()结合Math.floor(). 例如:

Math.floor(Math.random() * 101);  // returns a random integer from 0 to 100

对于日期生成,请参阅此答案

如果我包括间隔,它应该如下所示:

let generated_data = []; // this will be the final data
let colors = ["Blue", "Red", "Green"]; // define all the colors you need


function getRandomInt(min, max) { // generate random number
    return Math.floor(Math.random() * (max - min)) + min;
}

function capFirst(string) { // make the first letter capital letter
    return string.charAt(0).toUpperCase() + string.slice(1);
}


function generateName(){ //generates random Name
    var name1 = ["abandoned","able","absolute","adorable"]; // you can add more elements in this list, if you want a wider choice
    var name2 = ["people","history","way","art","world"]; // you can add more elements in this list, if you want a wider choice
    var name = capFirst(name1[getRandomInt(0, name1.length)]) + ' ' + capFirst(name2[getRandomInt(0, name2.length + 1)]);
    return name;
}


function randomDate(date1, date2){ // generates random date
    var date1 = date1 || '01-01-1970'
    var date2 = date2 || new Date().toLocaleDateString()
    date1 = new Date(date1).getTime()
    date2 = new Date(date2).getTime()
    if( date1>date2){
            return new Date(getRandomInt(date2,date1)).toLocaleDateString()   
    } else{
        return new Date(getRandomInt(date1, date2)).toLocaleDateString()  
    }
}

function generateRandomObject() { // adds a random object in the objects list
    let obj = {
        Id: getRandomInt(1, 1000),
        Subject: generateName(),
        StartTime: randomDate('01/01/2000', '01/01/2020'),
        EndTime: randomDate('01/01/2000', '01/01/2020'),
        CategoryColor: colors[getRandomInt(0, colors.length)]
    }
    generated_data.push(obj);
}


setInterval(generateRandomObject, 30 * 60 * 1000); // sets an interval of 30 mins in which the function  will be executed

推荐阅读