javascript - 使用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);
}
}
解决方案
您可以将其用于随机名称生成器。对于随机数生成器,您可以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
推荐阅读
- css - Grunt sass:压缩期间的换行符差异
- socket.io - Socket.io:如何处理两个用户加入同一个 DM 聊天室
- angular11 - 组件中更新的 Angular 11 变量未在模板中更新
- azure - 如何使用 labview 应用程序检索存储在 azure 或一个驱动器中的文件?
- android - Android RecyclerView LayoutOrientation 不起作用
- bison - 如何从 flex 调用 yyerror()?
- c# - 为什么零长度的 stackalloc 让 C# 编译器乐于允许有条件的 stackalloc?
- r - 根据匹配列将列复制到另一个数据框中
- c# - Bitmap.Save 出现 Null 异常的错误,但它显然已实例化
- django - Django 上的社交网络登录失败,回调 url 不匹配