Jquery-访问关联索引数组上的元素



我正在尝试使用以下代码从最短到最长对locations数组进行排序:

for(var i=0; i<locations.length;i++)
{
    var swapped = false;
    for(var j=locations.length; j>i+1;j--)
    { 
        if (locations[j]['distance'] < locations[j-1]['distance'])
        {
            var temp = locations[j-1];
            locations[j-1]=locations[j];
            locations[j]=temp;
            swapped = true;
        }
    }
    if(!swapped)
        break;
}

当我尝试运行该程序时,我在Firebug中得到以下错误:

locations[j] is undefined

我控制台记录了位置数组,这就是它的样子:

[Object { id="1", marker=U, more...}, Object { id="4", marker=U, more...}, Object { id="6", marker=U, more...}, Object { id="3", marker=U, more...}, Object { id="2", marker=U, more...}, Object { id="5", marker=U, more...}]

有没有一种方法可以对对象进行数字索引,同时保持对象数据的关联索引?

或者,如果我不得不在foreach循环中使用this.distance,有没有一种方法可以访问第I个+1或第I个-1元素?

您不能使用Javascript数组sort函数吗??

var arr = [{'value' : '456'},{'value':'123'}];
arr.sort(function(a,b){
    if(a.value>b.value){
        return 1;
    }else if(a.value<b.value){
        return -1;
    }else{
        return 0
    }
});

您从1开始到晚,记住数组键是索引,从0 开始

for(var j=locations.length-1; j>i+1;j--)
{ 
   console.log(j);
  if (locations[j-1]['distance'] && locations[j]['distance'] < locations[j-1]['distance'])
    {
        var temp = locations[j-1];
        locations[j-1]=locations[j];
        locations[j]=temp;
        swapped = true;
    }
}

您将在最后一个循环中遇到问题,所以我添加了if(locations[j-1]['distance'] ...

数组的索引从0到长度为1的

for(var j=locations.length; j>i+1;j--)

因此CCD_ 4超出的范围

最新更新