Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.8k views
in Technique[技术] by (71.8m points)

Javascript functional programming and dynamic values in an Array

I am trying to write a function that grabs the first 14 days (starting today) with momentJS. My function currently looks like

    let dateArr = Array(14).fill(moment())
    .map((date) => {
        return date.add(1, 'days')
    });

I understand that fill is for static values and not dynamic ones, so how would I go about fixing this up so that I have an array that has, ['11/12', '11/13', '11/14', etc...]

I think i need some sort of recursion so that it adds 1 day from the last iteratee, or else i think it'll just keep adding 1 day from today for each iteration


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Array(14).fill(moment())
    .map((date, i) =>  date.add(1, 'days').format('MM/DD'));

OUTPUT: (14)?["01/13", "01/14", "01/15", "01/16", "01/17", "01/18", "01/19", "01/20", "01/21", "01/22", "01/23", "01/24", "01/25", "01/26"]

UPDATE:

Start from today^

Array(14).fill(moment())
    .map((date, i) =>  {
if(i === 0) {
return date.format('MM/DD')
}
return date.add(1, 'days').format('MM/DD')
});

(14)?["01/12", "01/13", "01/14", "01/15", "01/16", "01/17", "01/18", "01/19", "01/20", "01/21", "01/22", "01/23", "01/24", "01/25"]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...