![](/img/trans.png)
[英]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.