-1

In the following code I want to access key, value dynamically in the for loop. How can I do it?

 s= {5: "456", 6: "123"} 
 var count = Object.keys(s).length
 for (var j_cnt=0;j_cnt<count;j_cnt++)
 {

 }

Note: I do not want a normal for loop since i need to something with the count

Hulk
  • 32,860
  • 62
  • 144
  • 215

2 Answers2

1

If you really need the count, define an external count variable and increment inside your for in loop:

var s     = {5: "456", 6: "123"},
    count = 0;

for (var key in s) {
    if (s.hasOwnProperty(key))
        console.log(s[key]);
    count++;
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • 1
    @Hulk -- What is the difference doing it your way or this? Both give the current index and both are set to stop at the Object keys' length. – tymeJV Sep 25 '13 at 12:58
1

This is not "best practice", but as you are specifically looking for the for loop ...

s= {5: "456", 6: "123"} 
var count = Object.keys(s).length;
for (var j_cnt=0; j_cnt<count; j_cnt++) {
   var theKey = Object.keys(s)[j_cnt];
   var theValue = s[theKey];
}
devnull69
  • 16,402
  • 8
  • 50
  • 61