在下面的代码中,我想在for循环中动态访问key,value。我该怎么办?
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
答案 0 :(得分: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++;
}
答案 1 :(得分: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];
}