我的脚本正在从php服务器端脚本获得一些数组。
result = jQuery.parseJSON(result);现在我要检查数组的每个变量。
if (result.a!='') { something.... }
if (result.b!='') { something.... }
....有什么更好的方法让它像php 'foreach‘,'while’或smth一样快速呢?
更新
这段代码(多亏了how代码)给出了数组中变量的值,但是我如何获得变量的名称呢?
for(var k in result) {
alert(result[k]);
}更新2
这就是php端的工作方式。
$json = json_encode(array("a" => "test", "b" => "test", "c" => "test", "d" => "test"));发布于 2011-10-05 14:35:57
你可以做这样的事
for(var k in result) {
console.log(k, result[k]);
}它循环遍历返回的json中的所有键并打印值。但是,如果您有一个嵌套结构,则需要使用
typeof result[k] === "object"以确定是否必须循环嵌套对象。我使用过的大多数API,开发人员都知道返回的结构,所以这是不必要的。然而,我认为这种期望可能并不是对所有情况都有好处。
发布于 2011-10-05 14:38:59
试试这个:
$.each(result,function(index, value){
console.log('My array has at position ' + index + ', this value: ' + value);
});发布于 2018-12-02 12:00:54
您可以使用.forEach()方法的JavaScript循环通过JSON。
var datesBooking = [
{"date": "04\/24\/2018"},
{"date": "04\/25\/2018"}
];
datesBooking.forEach(function(data, index) {
console.log(data);
});
https://stackoverflow.com/questions/7662997
复制相似问题