Javascript循环访问对象数组

时间:2014-07-31 09:28:16

标签: javascript arrays

我想使用JavaScript循环遍历一个对象数组

console.log($scope.filteredItems);

在控制台中返回10个对象的数组

Object {editionId: "6", detailId: "10"} 
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
length: 10
__proto__: Array[0]

目前的选择是10

我想使用prev和next按钮循环显示此过滤后的数组

HTML

<$scope.filteredItems/{{prevItem}}" class="btn btn-left">&lt;</a>
<$scope.filteredItems/{{nextItem}}" class="btn btn-right">&gt;</a>

请注意,这是来自数据库的过滤数组,并且递增可能只是在循环中循环 整个数据库不是过滤后的数组

这是我的努力

if ($scope.filteredItems.detailId > 0) {

    console.log($route.params);
    $scope.prevItem = Number($scope.filteredItems.detailId)-1;
} else {
    $scope.prevItem = $scope.data.products.length-1;
}

if ($scope.filteredItems.detailId < $scope.data.products.length-1) {
    $scope.nextItem = Number($scope.filteredItems.detailId)+1;
} else {
    $scope.nextItem = 0;
}

2 个答案:

答案 0 :(得分:1)

试试这个:

HTML:

<button id="prev">Prev</button>
<button id="next">Next</button>

<div id="data_value"></div>

JS代码:

$(document).ready(function(){
    var counter = 0;
    var arrObj = [{name:"sam1",age:20},{name:"sam2",age:22},{name:"sam3",age:24},{name:"sam4",age:26},{name:"sam5",age:28}];
    var totalcounter = 0;

    for (i in arrObj) {
        totalcounter++;
    }

    $("#data_value").text(arrObj[0].name+" - "+ arrObj[0].age);
    $("#prev").attr('data-rel',counter);
    $("#next").attr('data-rel',counter);

    $("#next").click(function(){
        if (counter < totalcounter - 1) {
            ++counter;
            $("#data_value").text(arrObj[counter].name+" - "+ arrObj[counter].age);
        }
    });

    $("#prev").click(function(){
        if (counter > 0) {
            --counter;
            $("#data_value").text(arrObj[counter].name+" - "+ arrObj[counter].age);
        }
    });       
}); 

答案 1 :(得分:0)

为了在DIR = +1 |的方向上循环长度为LEN的数组-1,从PREV到NEXT位置执行:

NEXT = (PREV + DIR + LEN) % LEN