Associate Array / Key Pair Array In Javascript arranged in with random order of keys.

余生长醉 提交于 2019-12-13 05:54:19

问题


Is it possible to have an Associate Array / Key Pair Array arranged in with random order of keys. Whenever, I am adding a new element, javascript is automatically sorting the keys.

For example,

When I'm creating an array as

a[T1001] ="B"
a[T1005] = "A"
a[T1003] ="C"

and later the array list is verified, I'm seeing that the array is automatically ordered as :

a[T1001]
a[T1003]
a[T1005] 

Is it possible to retain the same order in which I am assigning the values to the array ?. I cannot use the Push method.. It creates an indexed array with the individual objects added as its values.


回答1:


Looks to me as if your using an object. The sorting of an object's properties is never guaranteed. I don't think internet explorer (at least the old versions) sorts the properties but chrome does by default.

Your code is invalid, it should have the properties as strings if they are not numbers. And you would have to use an object

a = {};
a["T1001"] ="B"
a["T1005"] = "A"
a["T1003"] ="C"

You can either use two arrays to store your properties and the value if you want to preserve the ordering, or you cannot guarantee the ordering if you insist on using an object.

Two arrays

a1 = []; a2 = []
a1[0] = "T1001"; a2[0] = "B";
a1[1] = "T1005"; a2[1] = "A";
a1[2] = "T1003"; a2[2] = "C"; 

EDIT: Unless I guessed at what you meant wrong and that T1001, etc are variables containing numbers.




回答2:


Objects in JavaScript (and your "array" is just an object here) have no inherent order of their properties you can rely on.

As a workaround, you could store the order of keys in a separate array:

var order = [];

a['T1001'] = "B";
order.push( 'T1001' );
a['T1005'] = "A";
order.push( 'T1005' );
a['T1003'] = "C";
order.push( 'T1003' );

If you then traverse the order array, you can get your required order:

for( var i=0; i<order.length; i++ ) {
  console.log( a[ order[i] ] );
}

EDIT

Removing elements from the first list would require the use of indexOf and splice():

function delElement( arr, order, index ) {
  // get the position of the element within the order
  var position = order.indexOf( key );

  // delete element from list
  delete arr[ order[ pos ] ];

  // remove from ordering array
  order.splice( pos, 1 );
}


来源:https://stackoverflow.com/questions/17444480/associate-array-key-pair-array-in-javascript-arranged-in-with-random-order-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!