![](/img/trans.png)
[英]Javascript forEach() through an array: how to get the previous and next item?
[英]How to get next and previous item?
如何获得下一个项目,上一个项目? 例如,第3个活动项,当我单击下一个按钮时,该函数返回第5个项。
我的JSON数据:
const DataJ = [
{ date: '2018-05-17T15:11:23.351Z'},
{ date: '2018-01-17T15:11:23.351Z'},
{ date: '2018-10-17T15:11:23.351Z'},
{ date: '2018-10-17T15:11:23.351Z'},
{ date: '2018-12-17T15:11:23.351Z'}
];
上一个和下一个功能。
const nextItem = () => {
// Next json item
console.log();
}
const prevItem = () => {
// Prev json item
console.log();
}
<div>
<button type="button" className="control-btn" onClick="prevItem"> Prev </button>
<button type="button" className="control-btn" onClick="nextItem"> Next </button>
</div>
我尝试使用此方法:
const prevItem = () => {
const { DataJ } = this.props;
const curDate = new Date(Date.now());
console.log(DataJ[0]);
return DataJ.reduce(
(a, b) =>
new Date(b.date) <= curDate
? b : a,
DataJ[0]
);
}
这是您可以迭代项目的方式:
var myApp = window.MyApp || {}; const DataJ = [ { date: '2018-05-17T15:11:23.351Z'}, { date: '2018-01-17T15:11:23.351Z'}, { date: '2018-10-17T15:11:23.351Z'}, { date: '2018-10-17T15:11:23.351Z'}, { date: '2018-12-17T15:11:23.351Z'} ]; myApp.currentIndex = 0; myApp.currentItem = function () { return DataJ[myApp.currentIndex]; }; myApp.prevItem = function () { myApp.currentIndex--; return myApp.currentItem(); }; myApp.nextItem = function () { myApp.currentIndex++; return myApp.currentItem(); }; console.log(myApp.currentItem()); console.log(myApp.nextItem()); console.log(myApp.nextItem()); console.log(myApp.prevItem());
PS:您还应该考虑到达FIRST / LAST项目时会发生什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.