-1

在下面的代码中,我想在 for 循环中动态访问键、值。我该怎么做?

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

 }

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

4

2 回答 2

1

如果您真的需要计数,请定义一个外部count变量并在for in循环内递增:

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

for (var key in s) {
    if (s.hasOwnProperty(key))
        console.log(s[key]);
    count++;
}
于 2013-09-25T12:54:06.130 回答
1

这不是“最佳实践”,但是当您专门寻找 for 循环时...

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];
}
于 2013-09-25T12:58:39.567 回答