Search code examples
javascriptloopsfor-loopfor-in-loop

Access previous key/value 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?


Solution

  • No, 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];
         ...
      }