最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Sort array by key in JavaScript - Stack Overflow

programmeradmin0浏览0评论

I've created an array in JavaScript and inserted objects with keys of object_ids:

var ar = [];

ar[4] = 'a';
ar[2] = 'b';
ar[8] = 'c';
ar[5] = 'd';

Problem is when I print this out the array I get is:

[undefined, undefined, "b", undefined, "a", "d", undefined, undefined, "c"]

and

ar.length = 9

How do I prevent the array from auto filling with undefined values and simply save this array as a 4-element array?

Iteration over an array is not what I expect here.

Thanks!

I've created an array in JavaScript and inserted objects with keys of object_ids:

var ar = [];

ar[4] = 'a';
ar[2] = 'b';
ar[8] = 'c';
ar[5] = 'd';

Problem is when I print this out the array I get is:

[undefined, undefined, "b", undefined, "a", "d", undefined, undefined, "c"]

and

ar.length = 9

How do I prevent the array from auto filling with undefined values and simply save this array as a 4-element array?

Iteration over an array is not what I expect here.

Thanks!

Share Improve this question edited Aug 23, 2011 at 19:30 Nachshon Schwartz 15.8k20 gold badges63 silver badges99 bronze badges asked Aug 23, 2011 at 19:26 hszhsz 152k62 gold badges267 silver badges320 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 3

You can use an object literal instead of an array

var ar = {};
ar[4] = 'a';
ar[2] = 'b';
ar[8] = 'c';
ar[5] = 'd';
// {"2":"b","4":"a","5":"d","8":"c"}

You can iterate like this:

for (var i in a) {
    console.log(a[i]);
}

Here's what you are doing:

var ar = [];
ar[8] = 'c'; // creates [undefined, undefined, undefined, undefined, undefined, undefined, undefined, 'c'];

I believe this is what you want:

var ar = {};

ar[4] = 'a';
ar[2] = 'b';
ar[8] = 'c';
ar[5] = 'd';

Object.keys(ar).length == 4; // true

More information on Object.keys

I think you are confusing the behavior of JavaScript Arrays with the associative-array behavior of all JavaScript objects. Try this instead:

var a = {};
a[4] = 'a';
a[2] = 'b';
a[8] = 'c';
a[5] = 'd';
a; // {'2':'b', '4':'a', '8':'c', '5':'d'}

Note that the key/value pairs in an object are not ordered in any way. To order the keys or values you must maintain your own array of ordering.

what you want to do is probably:

array = {}
array["1"] = "b"
array["7"] = "aaa"

now array is:

 Object { 1="a", 7="b"}

is it right?

var arr = {
    0 : "hello",
    8 : "world",
    14: "!"
    };

var count = 0;
for (var k in arr) {
   ++count;
}

document.write(arr[0] + " " + arr[8] + arr[14] + " with a length of " + count );

Outputs hello world! with a length of 3

You can use an Object.. and here is how to collect the count (if you needed)

Fiddle

There is no guarantee that iterating an Object using the for...in statement be in any specific order. The behavior is undefined in ECMA Script specification, quote:

The mechanics of enumerating the properties ... is implementation dependent.

Chrome doesn't iterate elements in order in many cases, last time I checked Opera went the same way and just now I read here that IE9 has adopted the same behavior. So your only solution that is guaranteed to keep both the association and order of elements is to use an Object to store keys and values and an Array to store the order:

var obj = { 4: 'a', 2: 'b', 8: 'c', 5: 'd' };
var order = [ 4, 2, 8, 5 ];

for( var i in order ) {
    //do something with obj[ order[i] ]
}
发布评论

评论列表(0)

  1. 暂无评论