Iterating through a hash back in js
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.
+7
source to share
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
+1
source to share