JSON数组的foreach,语法 [英] foreach for JSON array , syntax
问题描述
我的脚本正在从php服务器端脚本获取一些数组.
my script is getting some array from php server side script.
result = jQuery.parseJSON(result);
现在我要检查数组的每个变量.
now I want to check each variable of the array.
if (result.a!='') { something.... }
if (result.b!='') { something.... }
....
还有什么更好的方法可以使其快速实现,例如php'foreach','while'或smth吗?
Is there any better way to make it quick like in php 'foreach' , 'while' or smth ?
更新
这段代码(感谢hvgotcodes)为我提供了数组内变量的值,但是我又如何获得变量名呢?
This code ( thanks to hvgotcodes ) gives me values of variables inside the array but how can I get the names of variables also ?
for(var k in result) {
alert(result[k]);
}
更新2
这是php side的工作方式
This is how php side works
$json = json_encode(array("a" => "test", "b" => "test", "c" => "test", "d" => "test"));
推荐答案
您可以做类似的事情
for(var k in result) {
console.log(k, result[k]);
}
循环遍历返回的json中的所有键并输出值.但是,如果您有嵌套结构,则需要使用
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"
确定是否必须遍历嵌套对象.我使用过的大多数API,开发人员都知道要返回的内容的结构,因此这是不必要的.但是,我认为这种期望可能不适用于所有情况.
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.
这篇关于JSON数组的foreach,语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!