Iterating through a hash back in js

So let's say I have a hash

a = { foo : "bar" , zap : "zip" , baz : "taz" }


I can interact with him this way

for( var n in a ) {


but I want to go back through it ...

thoughts on how to do this?


source to share

4 answers

There are no forwards or backwards in the objects, because the ordering is not specified by the specification. I'm sure there isn't even a guarantee that the two traversals will necessarily give you the property names in the same order.

(Strictly speaking, you also don't know that property names are hashed, although that doesn't really matter.)

If you need to maintain ordering (possibly according to the order in which properties are added), you will need to anchor the property store with something that supports a parallel array containing the keys. It can then expose the iterator APIs to allow forward and backward traversal.



var a = { foo : "bar" , zap : "zip" , baz : "taz" },
    propertycount = Object.keys(a).length,
    i = propertycount - 1;

for(i; i >= 0; i--){



Don't use hashes if you want to do an orderly traversal.

hashes ordered by design



a = { foo : "bar" , zap : "zip" , baz : "taz" }

for( var i=Object.keys(a).length-1; i>=0; --i){


Hmm, it looks like it works fine :)



All Articles