我想根據用戶插入的郵政編碼自動填充城市和州的值。我無法將輸入的郵政編碼與json對象中提供的郵政編碼進行比較。 OBJ長度的值是1,它必須是3obj的長度爲1 - javascript
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;
}
}
有一個在'obj'只需一個鍵, 'obj.zipcodes',這是一個數組,你可以用'for'循環來循環。 – Teemu