我正在尝试根据用户插入的邮政编码自动填充城市和州的值。我无法将输入的邮政编码与json对象中可用的邮政编码进行比较。 obj length的值为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;
}
}
最佳答案
解析后的对象变为:
{
"zipcodes":[
{"zip":"22031","city":"Fairfax" ,"State":"VA" },
{"zip":"22032","city":"AshBurn" ,"State":"VA" },
{"zip":"22033","city":"Tysons" ,"State":"VA" }]}
]
};
因此,对象的密钥数为1,即邮政编码。如果您想计算邮政编码,
用这个:
var obj = JSON.parse(text);
var n = obj.zipcodes.length;
关于javascript - obj的长度为1-JavaScript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33195888/