我正在尝试根据用户插入的邮政编码自动填充城市和州值。我无法将输入的邮政编码与json对象中提供的zip进行比较。 obj长度的值为1,必须为3.
var text = '{"zipcodes":[' +
'{"zip":"22031","city":"Fairfax" ,"State":"VA" },' +
'{"zip":"22032","city":"AshBurn" ,"State":"VA" },' +
'{"zip":"22033","city":"Tysons" ,"State":"VA" }]}';
var obj = JSON.parse(text);
var n = Object.keys(obj).length;
for(i=0; i<=n; i++){
if(obj.zipcodes[i].zip.parseInt() == zipcodes.parseInt()){
document.getElementById("city").value = obj.zipcodes[i].city;
document.getElementById("state").value = obj.zipcodes[i].State;
}
}
答案 0 :(得分:2)
解析后的对象变为:
{
"zipcodes":[
{"zip":"22031","city":"Fairfax" ,"State":"VA" },
{"zip":"22032","city":"AshBurn" ,"State":"VA" },
{"zip":"22033","city":"Tysons" ,"State":"VA" }]}
]
};
因此对象的密钥数是1,即zipcodes。如果你想要数量的邮政编码,
使用此:
var obj = JSON.parse(text);
var n = obj.zipcodes.length;
答案 1 :(得分:0)
Haven没有试过这段代码,但看起来你真的只得到了一个关键字,这就是&#39; zipcodes&#39;。
我认为你应该通过obj [&#39; zipcodes&#39;]来代替?
答案 2 :(得分:0)
是的,确实长度为1。 如果您想迭代邮政编码,那么对于上面给出的代码片段,我会这样做:
var n = obj.zipcodes.length;
//continue your computation here.