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?
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?
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.
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
dont use hashes if you want to do ordered traversal.
hashes arent ordered by design
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 :)