![](/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.