遍历在Javascript对象 [英] Iterating over objects in Javascript
问题描述
我有形式的obejct:
I have an obejct of the form:
var test = {"2011":{"10":4,"9":9,"8":15,"7":11,"6":11,"5":13,"4":9,"3":5,"2":9,"1":4,"0":20},"2010":{"11":9,"10":23,"9":58}}
我要遍历这个,所以我可以打每一个年份和月份组合。我有:
I want to iterate over this so I can hit each year and month combo. I have:
var years = d3.keys(test),
months = d3.range(12),
data = [];
所以,作为一个JavaScript新手,要完整性检查的事情,我检查年
。
document.writeln(years)
2011,2010
酷,但是当我尝试遍历年
阵列获取数据了测试
元素的我做我认为是正确的测试,但内容会丢失:
Cool, but when I try to iterate over the years
array to pull data out of test
the elements I do what I think is correct to test, but the elements are lost:
for(var y in years) {
document.writeln(y);
}
0,1
我如何遍历年
来得到实际的元素( 2011,2010
)在其中?
How do I iterate over years
to get the actual elements (2011,2010
) in them?
推荐答案
在
检索索引/键(不是值)。
for in
retrieves indices/keys (not the values).
您将需要修改你的循环,像这样:
You'll need to modify your loop, like so:
for(var y in years) {
document.writeln(years[y]);
}
修改 - 每missingno的评论,使用迭代数组在
是的坏主意。
EDIT - per missingno's comment, iterating over an array using for in
is a bad idea.
for(var i = 0, l = years.length; i < l; i++) {
document.writeln(years[i]);
}
一点点额外的信息......如果您使用了/在打击的对象循环同样会遍历你的属性键。例如,
A little extra information... if you use a for/in loop against an object it will also iterate over your property keys. For example,
for(var y in test) {
//This will yield, "2011" and then "2010"
document.writeln(y);
}
这篇关于遍历在Javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!