最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Access previous keyvalue in for-in loop - Stack Overflow

programmeradmin6浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 5

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];
     ...
  }
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?
}
发布评论

评论列表(0)

  1. 暂无评论