写一个随机生成数组的方法 类似于{sampleCode:'YP220916', sampleAddress: '建邦环境水务,sampleDate: '2022-09-16',sampleResult: '正常',reportTime: '2022-09-16'} 其中sampleCode和日期有关
时间: 2023-05-26 07:01:58 浏览: 88
随机数生成方法
function generateSampleData(n) {
let sampleData = [];
let sampleAddressList = ['建邦环境水务', '垃圾处理公司', '化工厂', '水泥厂'];
let sampleResultList = ['正常', '超标', '异常'];
for (let i = 0; i < n; i++) {
let sampleCode = 'YP' + Math.random().toString(36).substr(2, 6) + (i + 1).toString().padStart(2, '0');
let sampleAddress = sampleAddressList[Math.floor(Math.random() * sampleAddressList.length)];
let sampleDate = generateSampleDate();
let sampleResult = sampleResultList[Math.floor(Math.random() * sampleResultList.length)];
let reportTime = generateReportTime(sampleDate);
sampleData.push({ sampleCode, sampleAddress, sampleDate, sampleResult, reportTime });
}
return sampleData;
}
function generateSampleDate() {
let year = Math.floor(Math.random() * 10) + 2021;
let month = Math.floor(Math.random() * 12) + 1;
let day = Math.floor(Math.random() * 28) + 1;
return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
}
function generateReportTime(sampleDate) {
let date = new Date(sampleDate);
let hours = Math.floor(Math.random() * 24);
let minutes = Math.floor(Math.random() * 60);
let seconds = Math.floor(Math.random() * 60);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(seconds);
return date.toISOString().substr(0, 19).replace('T', ' ');
}
// 调用示例
console.log(generateSampleData(5)); // 生成5个样本数据的数组,并输出结果
阅读全文