开发者

Javascript For loop doesn't always work in IE

开发者 https://www.devze.com 2023-03-23 15:21 出处:网络
After two days of searching, I\'m stuck and could really use some assistance. I have a javascript array that when iterated through will give me the key to each subsequent array.This works in all brow

After two days of searching, I'm stuck and could really use some assistance.

I have a javascript array that when iterated through will give me the key to each subsequent array. This works in all browsers except for some versions of IE. In some versions of IE, it appears that it first reorders the array in ascending order before returning the key. Jquery's each function does the same. Is there an equivalent to the javascript for loop that will not reorder the array and would still work for everyone?

var db = new Array();
db[259] = new Array(3);
db[259][0] = "John Smith";
db[259][1] = "Los Angeles";
db[259][2] = "Chicago";

db[917] = new Array(3);
db[917][0] = "Jane Smtih";
db[917][1] = "New York";
db[917][2] = "Tampa";

db[208] = new Array(3);
db[208][0] = "Jack Johnson";
db[208][1] = "Baltimore";
db[208][2] = "Milwaukee";

for(var i in db){document.write(i + " ");}

In most browsers, the 开发者_JAVA百科above will output 259 917 208. This is the outcome that I would like.

In some versions of IE, the above will output 208 259 917. It looks like it orders the keys in ascending order first. The key is important here as it is the person's ID # and the rank is important (ie, 259 should come before 208). Other functions make reference to db[i] where i is the person's ID #.

Can anyone help?


The order of iteration for Arrays is not guaranteed in JavaScript for-in loops; however, most JS implementations order the indices naturally (except, of course, older versions of IE).

If you know the indices ahead of time you should store them separately for explicit iteration:

var idxs = [259, 917, 208], i;
for (i=0; i<idxs.length; i++) {
  document.write(db[idxs[i]]);
}


For...in isn't meant for Arrays in JavaScript and does not guarantee order it is meant for Object (which an Array happens to be which is why it "works"). Use a proper for or while loop

Reference: For...in


You might want to look at jQuery's each() function.

0

精彩评论

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