我正在尝试遍历如下所示的JSON数组-
var results = [{"city_name":"Bradford","counter":1},{"city_name":"Aberdeen","counter":1},{"city_name":"Aberfeldy","counter":1},{"city_name":"Aberaeron","counter":1},{"city_name":"Aberdare","counter":0},{"city_name":"Abergavenny","counter":0},{"city_name":"Abergele","counter":0}];
for(var i = 0; i < results.length; i++) {
var obj = results[i];
console.log(obj.city_name);
console.log(obj.counter);
}
但我得到的所有信息在警报中均未定义。
答案 0 :(得分:0)
它的工作
let results=[{"city_name":"Bradford","counter":1},{"city_name":"Aberdeen","counter":1},{"city_name":"Aberfeldy","counter":1},{"city_name":"Aberaeron","counter":1},{"city_name":"Aberdare","counter":0},{"city_name":"Abergavenny","counter":0},{"city_name":"Abergele","counter":0}]
for(var i = 0; i < results.length; i++) {
var obj = results[i];
console.log(obj.city_name);
console.log(obj.counter);
}
//second way
results.forEach(a=>{
console.log(a.city_name);
console.log(a.counter);
})
答案 1 :(得分:0)
不太了解您,但也许是帮助
const results = [{"city_name":"Bradford","counter":1},{"city_name":"Aberdeen","counter":1},{"city_name":"Aberfeldy","counter":1},{"city_name":"Aberaeron","counter":1},{"city_name":"Aberdare","counter":0},{"city_name":"Abergavenny","counter":0},{"city_name":"Abergele","counter":0}]
for(let i in results) {
console.log("city_name",results[i].city_name);
console.log("counter",results[i].counter);
}
答案 2 :(得分:0)
我尝试了您的代码,它可以工作。但最好这样写:
results.forEach(result => alert(result.city_name));
无论如何,它甚至可以与您的语法一起使用。