Javascript循环遍历对象数组

Javascript cycling through an object array

本文关键字:数组 对象 遍历 循环 Javascript      更新时间:2023-09-26

我想使用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;
}

试试这个:

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);
        }
    });       
}); 

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

NEXT = (PREV + DIR + LEN) % LEN