javascript - Sort array by key OR: Why is my for loop executing out of order? -
I have some objects that I need to keep in a certain order based on some configuration data. There is a problem in replicating through the array in I thought that if I made the array and then stepped through the loop, then I could execute the code correctly. It is doing a great job except for a usage case, in which I add the fourth object to the array and then move to the third position.
link [0] = foo link [1] = bar link [2] = foobar link [3] = a_herring link [4] = a_shrubery order = [] // json-loaded Gone, numbers 1 2 3 or 4 in the form are in the form of //: order [0] = 1 order [1] = 2 order [2] = 4 order [3] = wrong order [4] = 3 order (x in order) {if (x [x]) {printOrder [order [x]] = links [X] // Remember that in this case the order will be [0]} This should give me an array that looks like this:
// var print order [undefined, foo, bar, e-turban But when I try again via the array: for (in printOrder x) {PrintOrder [x] .link.appendChild (Printordr [x] Kimage) Printordr [x] .appendChild (Printordr [x] .link) Printordr [x] .appendChild (Printordr [x] .text) document.getElementById ( "myDiv") .appendChild (PrintOrder [x]); } I get foo, bar, foobar, a_shrubbery as the output instead. I need to sort this array with the key value, or step through it in the correct order.
The numerical properties of array examples should always be followed with a numerical index:
for (var x = 0; x & lt; printOrder.length; ++ x) {// print order with whatever [x]} Using the phrase "for ... in" as the statement you will not get the predicted order, as you have seen, and it may have other strange effects (especially when you mix in the JavaScript framework or South libraries or whatever). It is used to run through the attribute names of an object, and it does not specifically treat arrays.
Comments
Post a Comment