开发者

Sort array by key OR: Why is my for loop executing out of order?

I have an array of objects which I need placed in a certain order, depending on some configuration data. I am having a problem with itterating through the array in the proper order. I thought that if I made the 开发者_高级运维array, and then stepped through with a for loop, I would be able to execute the code correctly. It is working great except in one use case, in which I add the fourth item to the array and then go back to the third.

links[0] = foo
links[1] = bar
links[2] = foobar
links[3] = a_herring
links[4] = a_shrubery

order = [] //loaded from JSON, works has the numbers 1 2 3 or 4 as values
           //in this case:
order[0] = 1
order[1] = 2
order[2] = 4
order[3] = false
order[4] = 3

for(x in order){        
   if(order[x]){
    printOrder[order[x]]=links[x]
    //remember that in this case order[0] would
}

This should give me an array that looks like this:

//var printOrder[undefined,foo,bar,a_shrubbery,foobar]

But when I try to itterate through the array:

    for(x in printOrder){
        printOrder[x].link.appendChild(printOrder[x].image)
        printOrder[x].appendChild(printOrder[x].link)
        printOrder[x].appendChild(printOrder[x].text)
        document.getElementById("myDiv").appendChild(printOrder[x]);
    }

I get foo, bar, foobar, a_shrubbery as the output instead.

I need to either sort this array by key value, or step through it in the correct order.


Iterating over the numerically-index properties of Array instances should always be done with a numeric index:

for (var x = 0; x < printOrder.length; ++x) {
  // whatever with printOrder[x]
}

Using the "for ... in" form of the statement won't get you predictable ordering, as you've seen, and it can have other weird effects too (particularly when you mix in JavaScript frameworks or tool libraries or whatever). It's used for iterating through the property names of an object, and it doesn't treat Array instances specially.


You need to create a function for finding values in an array like this:

Array.prototype.indexOf = function(value)
{
    var i = this.length;

    while ( i-- )
    {
            if ( this[ i ] == value ) return i;
    }

    return -1;
};

You can then use it like this:

//NOTICE: We're looping through LINKS not ORDER
for ( var i = 0; i < links.length; i++ )
{
    var index = order.indexOf( i );

    //It's in the order array
    if ( index != -1 ) printOrder[ i ] = links[ i ];
}

REMEMBER: You need to make sure the values returned in json are integers. If they're strings, then you'll need to convert the integers to string when passed to indexOf.


The function you have in your question works as you suggest it should.

http://jsfiddle.net/NRP2D/8/ .

Clearly in this simplified case you have removed whatever error you are making in the real case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜