Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE9 associative array

Fruit={4:"apple",2:"banana",3:"graps"}; 
var k;
for(k in Fruit)
{alert(k);}

alert will be 2 3 4 in sequence in Ie9 when In IE8 & FF & other browse give 4 2 3 help me out of this. I need sequence is 4 2 3

like image 945
Ankit Thakkar Avatar asked Jan 16 '23 20:01

Ankit Thakkar


2 Answers

You cannot control the order that keys come out of an object in JavaScript. If you care about the order, put the keys in a separate array:

var fruit = { 4:"apple", 2:"banana", 3:"grapes" };
var fruitKeys = [ 4, 2, 3 ]
for (var i=0, l=fruitKeys.length; i<l; ++i) {
  var k = fruitKeys[i];
  alert(k + ":" + fruit[k]);
}

(as a point of style, you also shouldn't capitalize variable names; use capitals only for functions that you're using as constructors/"classes").

fiddle

like image 113
Mark Reed Avatar answered Jan 19 '23 11:01

Mark Reed


Associative arrays don't have order, so IE9's behavior here is not incorrect. There is no existing data type that can store the order this way. Your best bet would be to store the order explicitly:

var Fruit = [[4, "apple"], [2, "banana"], [3, "graps"]];
for (var i = 0; i < Fruit.length; i++) {
    alert(Fruit[i][0]);
}
like image 36
kojiro Avatar answered Jan 19 '23 09:01

kojiro