3

So lets say I have a hash

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

I can interate over it like this

for( var n in a ) {
 doSomething(a[n]);
}

but I want to go backwards through it...

thoughts on how to do this?

samccone
  • 10,746
  • 7
  • 43
  • 50
  • 1
    Duplicate of http://stackoverflow.com/questions/4956256/loop-through-associative-array-in-reverse? – Ben Simpson Mar 29 '12 at 17:20
  • This is not a `regular for` statement, it's similar to `foreach`. And in `foreach` there is no order. So you can't go back and forward – MatuDuke Mar 29 '12 at 17:20

4 Answers4

7

There is no forwards or backwards with object properties, as there is no ordering defined by the specification. I'm pretty sure that there's not even a guarantee that two traversals will necessarily give you the property names in the same order.

(Strictly speaking, you also don't know that the property names are hashed, though that doesn't matter much.)

If you need to maintain an ordering (perhaps according to the order in which properties have been added), you'd have to wrap up the property storage with something that maintained a parallel array containing the keys. It could then expose iterator APIs to allow traversal forwards and backwards.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1
var a = { foo : "bar" , zap : "zip" , baz : "taz" },
    propertycount = Object.keys(a).length,
    i = propertycount - 1;


for(i; i >= 0; i--){
    console.log(a[Object.keys(a)[i]]);            
}

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys


http://jsfiddle.net/ddFqD/

Alex
  • 34,899
  • 5
  • 77
  • 90
1

dont use hashes if you want to do ordered traversal.

hashes arent ordered by design

cpjolicoeur
  • 12,766
  • 7
  • 48
  • 59
0
a = { foo : "bar" , zap : "zip" , baz : "taz" }

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

Hmm this seems to work fine :)

samccone
  • 10,746
  • 7
  • 43
  • 50
  • this is totally different than your original question. plus you arent using the native hash anymore like you original asked about. you are creating a whole new ordered array over which you are traversing – cpjolicoeur Mar 29 '12 at 17:29