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

时间:2012-01-22 07:38:21

标签: jquery arrays indexing

我正在尝试使用以下代码将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

我在console.log中找到了位置数组,这就像它的lloks:

[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个元素?

3 个答案:

答案 0 :(得分: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)

数组的索引是从0到length-1

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

所以locations[j]超出范围

答案 2 :(得分: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'] ...