Foreach for JSON array,语法

我的脚本正在从 php 服务器端脚本获取一些数组。

result = jQuery.parseJSON(result);

现在我要检查数组的每个变量。

if (result.a!='') { something.... }
if (result.b!='') { something.... }
....

有没有什么更好的方法可以像 php 中的 foreach、 while 或 smth 那样快速实现?

更新

这段代码(感谢 hvgotcode)给出了数组中变量的值,但是我怎样才能得到变量的名称呢?

for(var k in result) {
alert(result[k]);
}

更新2

PHP 就是这么运作的

$json = json_encode(array("a" => "test", "b" => "test",  "c" => "test", "d" => "test"));
402490 次浏览

You can do something like

for(var k in result) {
console.log(k, result[k]);
}

which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use

typeof result[k] === "object"

to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.

Sure, you can use JS's foreach.

for (var k in result) {
something(result[k])
}

Try this:

$.each(result,function(index, value){
console.log('My array has at position ' + index + ', this value: ' + value);
});

You can use the .forEach() method of JavaScript for looping through JSON.

var datesBooking = [
{"date": "04\/24\/2018"},
{"date": "04\/25\/2018"}
];
    

datesBooking.forEach(function(data, index) {
console.log(data);
});