[英]Generate one random index from an array but exclude one. javascript
[英]Generate random date but exclude some dates from array in javascript
我有一个名为dates的数组,其中包含一些日期。 我想排除这些日期并生成一个从今天开始的新随机日期。
dates = [20/2/2020,10/2/2019] //需要排除日期
到目前为止,我已经尝试过,
var new_dif = Math.random(); //generates random number
var daea = new Date(new_dif); //new random date
alert(daea); //generates new date with year 1970
您可能想尝试这样的事情(在未来一年的某个地方设置随机日期)。
const now = (new Date()).getTime();
const newDiff = parseInt(Math.random() * 1000 * 60 * 60 * 24 * 365, 10);
const otherDate = new Date(now + newDiff);
console.log(otherDate);
然后你需要检查你的排除数组,看看它们是否匹配。 如果没有,那么你很好用它。
或者在使用循环时:
function getRandomDate() { var now = Date.now(); var newDiff = parseInt(Math.random() * 1000 * 60 * 60 * 24 * 365, 10); var otherDate = new Date(now + newDiff); return otherDate; }; var excludedDates = ['2020-02-20', '2019-02-10']; var duplicate = true; while (duplicate) { var getMyDate = getRandomDate(); duplicate = false; excludedDates.forEach((excludedDate) => { var excludedInMs = (new Date(excludedDate)).getTime(); if (excludedInMs === getMyDate) { duplicate = true; } }); if (.duplicate) { console,log('while >>>>'; getMyDate); } }
const randomDateFromToday = (exclude_dates, max_days = 365) => { const randomDate = () => { const rand = Math.floor(Math.random() * max_days) * 1000 * 60 * 60 * 24; const dat = new Date(Date.now() + rand); return `${dat.getDate()}/${dat.getMonth() + 1}/${dat.getFullYear()}`; }; let rday = randomDate(); while (exclude_dates.some((date_str) => date_str === rday)) { rday = randomDate(); } return rday; }; dates = ["20/2/2020", "10/2/2019"]; console.log(randomDateFromToday(dates)); console.log(randomDateFromToday(dates));
如果我想建议下一个日期不是随机的,而是从数组中最接近的日期怎么办?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.