I'm using a javascript associative array (arr) and am using this method to loop through it.
for(var i in arr) {
var value = arr[i];
alert(i =") "+ value);
}
The problem is that the order of the items is important to me, and it needs to loop through from last to first, rather than first to last as it currently does.
Is there a way to do this?
So as we can see in the example above, we can easily loop through indexed array using for loop. But for Associative Arrays we need to use ForEach loop.
For example, the following statement defines an associative array a with key signature [ int, string ] and stores the integer value 456 in a location named by the tuple [ 123, "hello" ]: a[123, "hello"] = 456; The type of each object contained in the array is also fixed for all elements in a given array.
Yes, in Google Chrome in 2016, array. reverse is at least twice faster than anything else.
Associative arrays are used to store key value pairs. For example, to store the marks of different subject of a student in an array, a numerically indexed array would not be the best choice.
Four things:
JavaScript has arrays (integer-indexed [see comments below]) and objects (string-indexed). What you would call an associative array in another language is called an object in JS.
You shouldn't use for in
to loop through a JS array.
If you're looping through an object, use: hasOwnProperty
.
JavaScript doesn't guarantee the order of keys in an object. If you care about order, use an array instead.
If you're using a normal array, do this:
for (var i = arr.length - 1; i >= 0; i--) {
//do something with arr[i]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With