简体   繁体   English

创建“下一个”和“上一个”按钮以使用索引在数组中导航?

[英]Creating “Next” and “Previous” buttons to navigate through an array using index?

I am trying to implement "Next" and "Previous" button to help me navigate through items in an array.我正在尝试实现“下一个”和“上一个”按钮来帮助我浏览数组中的项目。

I am using the index of items in the array to get the next or the previous item.我正在使用数组中项目的索引来获取下一个或上一个项目。

Example:例子:

  arrA =  [{_id:1,name:"T-Rex"},{_id:3,name:"Predator X"},{_id:4 ,name:"Velociraptor"},{_id: 6, name:"Triceratops"}]

The the id of the current object is represent by当前 object 的 id 表示为

var selectedID = _id

Next and Previous functions下一个和上一个功能

  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
  }

}

The expected outcome is that when I click either of the buttons, it should take me to the immediate next or previous item, but the actual outcome is that it loops through the array non-stop.预期的结果是,当我单击任一按钮时,它应该将我带到下一个或上一个项目,但实际结果是它不停地循环遍历数组。

Everything becomes much simpler when modulo (%) is used.当使用模数 (%) 时,一切都会变得简单得多。 It allows you to advance (forwards or backwards) in a list without worrying if you come at the beginning or end.它允许您在列表中前进(前进或后退),而不必担心您是在开头还是结尾。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM