Access previous key / value in inline loop

I am new to javascript, so please excuse me if something is obvious.

Suppose 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? } 

Can I access the previous or next key / value pair in a for-in loop?

+4
source share
3 answers

No, there is no direct way. One way would be to use a for loop on top of keys instead of for..in and select elements by their numerical index:

  keys = Object.keys(myObj); for(var i = 0; i < keys.length; i++) { current = keys[i]; previous = keys[i - 1]; next = keys[i + 1]; ... } 
+2
source
 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 the new value lastobj in the last loop, and during the loop you get the value "in memory". The if is mainly related to the first run of the loop when lastobj is still empty.

0
source

Try

 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? } 
-1
source

Source: https://habr.com/ru/post/1491084/


All Articles