通过选定的数字索引迭代数组

时间:2017-11-19 19:46:19

标签: javascript jquery arrays

只知道所需数组项的索引,我想知道它的键值。从下面的数组中它应该只返回:3例如。

理想情况下,我也喜欢上一个和下一个id。

JSON

//array to search - JSON
var steps = [{"id":"1"},{"id":"3"},{"id":"4"}];

HTML

<a href="#" class="steps" data-index="2">Step</a> 
 <!-- Data-index is the numeric index of the desired item -->

JQuery的

$(document).on('click','.steps', function() {
  clickedindex = $(this).data('index');
  //return the ID value here.
});

这是我的笔:https://codepen.io/omarel/pen/eeyXmW

2 个答案:

答案 0 :(得分:0)

这就是答案。(根据评论中收到的一些指示汇总)

这将从数组元素返回标记为ID的键的值,方法是仅使用所需的索引值迭代数组。

迭代的数组。

var steps = [{"id":"1","a":"a"},{"id":"3","b":"b"},{"id":"4","c":"c"}];

Jquery的

$(document).on('click','.steps', function() {
  clickedindex = $(this).data('index');
  //return the key value of "id" key.

   //answer
   currentstep = steps[clickedindex];
   console.log(currentstep["id"]); 

});

codepen:https://codepen.io/omarel/pen/eeyXmW?editors=1111

答案 1 :(得分:0)

数组是0-base,所以在你的例子中,索引2指向id 4.假设你的意思是data-index = 1,而上一个和下一个不是空的,那么这可以解决你的问题,如果我理解你的问题权利:

var prev, current, next; 
$(document).on('click','.steps', function() {
    clickedindex = $(this).data('index');
    prev = steps[clickedindex - 1].id;
    current = steps[clickedindex].id;
    next = steps[clickedindex + 1].id;
    console.log(prev + ' ' + current + ' ' + next ); 
});

您可以根据需要使用prev,current和next。