如何为数组中的每个元素创建唯一的日期?

我正在制作 React 应用程序,我有这样的问题:


例如,我有一个数组,它看起来像这样:container


const container = [

 {item: '1'},

 {item: '2'},

 {item: '3'},

 {item: '4'}

]

然后我想在html 4列中制作,每个列都有一个值。所以我正在使用这个:


<div>

 {container.map(t =>

  <div className='box'>{t.item}</div>

 )}

</div>

因此,它将生成具有不同值的 4:div1/2/3/4


现在我的问题在这里:如何为每个日期(从toda到...)制作自己的日期?box


第一项 = 6 月 8 日,星期一

第二个项目 = 6月9日,星期二

等。


我做了这样的事情,但它只显示当前日期,bu我需要显示从今天开始的接下来几天:8,9,10,11等(最后一个日期没关系,它可以是6月25日)



let x = new Date();


let fullDate = x.toLocaleString('en-gb', { day:'numeric' , weekday: 'long', month: 'long' });

附言:当我使用它时,它会在每列中显示所有日期。for


郎朗坤
浏览 61回答 2
2回答

慕妹3146593

执行此操作的一种方法是在每个对象中添加 date 属性。container你在你的问题中没有提到它,但通过这个例子,我理解你要求日期每天增加。为此,您可以将N天添加到当前日期,请查看以下示例,addDays函数将每个参数花费的天数添加到今天const container = [&nbsp; {&nbsp; &nbsp; item: 1,&nbsp; &nbsp; date: new Date(),&nbsp; },&nbsp; {&nbsp; &nbsp; item: 2,&nbsp; &nbsp; date: addDays(1),&nbsp; },&nbsp; {&nbsp; &nbsp; item: 3,&nbsp; &nbsp; date: addDays(2),&nbsp; },&nbsp; {&nbsp; &nbsp; item: 4,&nbsp; &nbsp; date: addDays(3),&nbsp; },];function addDays(day) {&nbsp; const date = new Date();&nbsp; date.setDate(date.getDate() + day);&nbsp; return date;}console.log(container);更新 0// container state after fetching dataconst container = [&nbsp; {&nbsp; &nbsp; item: 1,&nbsp; },&nbsp; {&nbsp; &nbsp; item: 2,&nbsp; },&nbsp; {&nbsp; &nbsp; item: 3,&nbsp; },&nbsp; {&nbsp; &nbsp; item: 4,&nbsp; },];// container state after transformconst list = container.map((entry) => ({&nbsp; ...entry,&nbsp; date: addDays(entry.item),}));function addDays(day) {&nbsp; const date = new Date();&nbsp; date.setDate(date.getDate() + day);&nbsp; return date;}console.log(list);更新 1为了格式化日期,您可以尝试类似这样的东西function format(date) {&nbsp; const month = date.getMonth()&nbsp; const day = date.getDate()&nbsp; return `${month}-${day}`;}并以这种方式调用格式方法function addDays(day) {&nbsp; const date = new Date();&nbsp; date.setDate(date.getDate() + day);&nbsp; return format(date);}您可以在这个超级受欢迎的问题中阅读有关日期格式的信息然后在 react 容器列表中,它变得简单<div>&nbsp; {container.map((t) => (&nbsp; &nbsp; <div className="box">&nbsp; &nbsp; &nbsp; <span>{t.item}</span>&nbsp; &nbsp; &nbsp; <span>{t.date}</span>&nbsp; &nbsp; </div>&nbsp; ))}</div>;

RISEBY

您可以使用此函数生成随机日期function randomDate(start, end) {&nbsp; &nbsp; return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));}//resultconst myRandomDate = randomDate(new Date(2020, 6, 8), new Date())console.log(myRandomeDate)将日期添加到对象列表中const newContainer =[]&nbsp;container.forEach(c=>{&nbsp; newContainer.push( { item:c.item , date:randomDate(new Date(2020, 6, 8), new Date()) })})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript