繁体   English   中英

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

[英]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.

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