在下面的代码中,我想在 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
在下面的代码中,我想在 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
如果您真的需要计数,请定义一个外部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++;
}
这不是“最佳实践”,但是当您专门寻找 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];
}