for in loop. reverse traverse

  • Thread starter R. Rajesh Jeba Anbiah
  • Start date
R

R. Rajesh Jeba Anbiah

Unfortunately, I couldn't find any way to traverse the object array in
reverse order. I'd thought there must be a way to do it with for..in
loop, but couldn't find anything yet. Could someone please help me?
TIA.
 
M

Michael Winter

Unfortunately, I couldn't find any way to traverse the object array in
reverse order.

What's an object array?
I'd thought there must be a way to do it with for..in loop, but couldn't
find anything yet.

The for..in statement doesn't return values in any particular order so
reversing is not possible.

[snip]

Mike
 
J

Joakim Braun

R. Rajesh Jeba Anbiah said:
Unfortunately, I couldn't find any way to traverse the object array in
reverse order. I'd thought there must be a way to do it with for..in
loop, but couldn't find anything yet. Could someone please help me?
TIA.

A probably meaningless hack would be to do a for...in with the object and
save the property names in an array. Then traverse that array backwards and
access the named properties of the first object.

Joakim Braun
 
G

Grant Wagner

comp.lang.javascript FAQ - http://jibbering.com/faq
Joakim Braun said:
"R. Rajesh Jeba Anbiah" <[email protected]> skrev i meddelandet

A probably meaningless hack would be to do a for...in with the object and
save the property names in an array. Then traverse that array backwards and
access the named properties of the first object.

But the values retrieved with for...in aren't guaranteed to be in any
particular order in the first place, so "reverse order" has no meaning,
since you can't be sure what the "forward order" will be.

If you want to store key/value pairs and be guaranteed of their order,
you will need to store both the key/value pair and the order they are
added in:

function MyOrderedMap() {
var keys = [];
var values = [];

this.add = function(key, value) {
// test to make sure 'key' isn't in 'keys'
var ii = keys.length;
while (ii-- > 0) {
if (key == keys[ii]) {
return false;
}
}
keys.push(key);
values.push(values);
return true;
}
this.getKeysInReverseOrder = function() {
return keys.reverse();
// or return keys.reverse().join(',');
// or whatever you want
}
}

You probably want methods for getting a value when passed a key:

this.getValue = function(key) {
var ii = keys.length;
while (ii-- > 0) {
if (key == keys[ii]) {
return values[ii];
}
}
return null;
}

and other methods as well to clear the list, etc.

I threw this together in a hurry, there may be syntax errors.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top