[英]Creating “Next” and “Previous” buttons to navigate through an array using index?
我正在嘗試實現“下一個”和“上一個”按鈕來幫助我瀏覽數組中的項目。
我正在使用數組中項目的索引來獲取下一個或上一個項目。
例子:
arrA = [{_id:1,name:"T-Rex"},{_id:3,name:"Predator X"},{_id:4 ,name:"Velociraptor"},{_id: 6, name:"Triceratops"}]
當前 object 的 id 表示為
var selectedID = _id
下一個和上一個功能
next(){
var idx = arrA.map(x => x._id).indexOf(selectedID);
if (idx === arrA.length - 1){
//return first item
var next_name = arrA[0].name;
} else {
var next_name = arrA[idx + 1].name
}
previous(){
var idx = arrA.map(x => x._id).indexOf(selectedID);
if (idx === arrA[0]){
// return last item
var prev_name = arrA[arrA.length -1].name;
} else{
var prev_name = arrA[idx -1].name
}
}
預期的結果是,當我單擊任一按鈕時,它應該將我帶到下一個或上一個項目,但實際結果是它不停地循環遍歷數組。
當使用模數 (%) 時,一切都會變得簡單得多。 它允許您在列表中前進(前進或后退),而不必擔心您是在開頭還是結尾。
const arr = [{_id:1,name:"T-Rex"},{_id:3,name:"Predator X"},{_id:4,name:"Velociraptor"},{_id: 6, name:"Triceratops"}] let currentIndex = 0; let currentId = arr[0]._id; // initial log log(); function next(){ move(); } function previous(){ move(false); } function move(advance = true){ currentIndex = (currentIndex + (advance? 1: -1) + arr.length) % arr.length; currentId = arr[currentIndex]._id; log(); } function log(){ console.log("Index: " + currentIndex, "Id: " + currentId); }
<button onclick="previous();">Previous</button> <button onclick="next();">Next</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.