I am new to javascript so please excuse me if its something obvious.
Lets say I have a for-in loop as follows...
for( var key in myObj ){
alert("key :" + myObj[key] ); // accessing current key-value pair
//how do I access previous element here?
}
Is it possible to access previous or next key/value pair in for-in loop?
I am new to javascript so please excuse me if its something obvious.
Lets say I have a for-in loop as follows...
for( var key in myObj ){
alert("key :" + myObj[key] ); // accessing current key-value pair
//how do I access previous element here?
}
Is it possible to access previous or next key/value pair in for-in loop?
Share Improve this question edited Jul 12, 2013 at 9:31 georg 215k56 gold badges322 silver badges399 bronze badges asked Jul 12, 2013 at 9:22 Pratik PatelPratik Patel 1,3553 gold badges17 silver badges45 bronze badges 1- 2 Why dont you giv it a try..? – 웃웃웃웃웃 Commented Jul 12, 2013 at 9:23
4 Answers
Reset to default 5No, there's no direct way. One workaround would be to use a for
loop over keys
instead of for..in
and pick elements by their numeric index:
keys = Object.keys(myObj);
for(var i = 0; i < keys.length; i++) {
current = keys[i];
previous = keys[i - 1];
next = keys[i + 1];
...
}
var lastobj = '';
for( var key in myObj ){
alert("key :" + myObj[key] ); // accessing current key-value pair
if(lastobj) {
//do things with last object here using lastobjs
}
lastobj = myObj[key]
}
Give a new value to lastobj last in loop and you will have the value "in memory" during the loop. The if
statement is mostly because of the first loop run, when lastobj is empty yet.
Couldn't you just say at the end of a loop something like:
previousKey = key
Then you can use previousKey in your next loop? This is something I do in my own small scripts, I'm by no means good at scripting but this has worked for me so far.
Try like
var prev = '';
for( var key in myObj ){
alert("key :" + myObj[key] ); // accessing current key-value pair
if(prev)
alert('Prev key :'+prev);
prev = myobj[key];
//how do I access previous element here?
}