my script is getting some array from php server side script.

result = jQuery.parseJSON(result);

现在我想判断数组的每个变量.

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

有没有更好的方法让它像php中的‘foreach’、‘while’或smth那样更快呢?

UPDATE

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]);
}

UPDATE 2

这就是php端的工作原理

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

推荐答案

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.

Jquery相关问答推荐

哪个 JQuery Select 器会排除与给定 Select 器匹配的父项的项目?

更改高亮 colored颜色

如何像这样通过 $.ajax ( serialize() + extra data ) 添加数据

递归循环遍历对象(树)

如何用另一个响应替换窗口的 URL 哈希?

$.each() 与 for() 循环 - 和性能

jQuery 动画滚动

JSON字符串到JS对象

如何在jQuery中 Select 具有特定ID的所有元素?

如何从表格单元格 (td) 中获取相应的表格标题 (th)?

复选框值始终为打开

Bootstrap 折叠动画不流畅

使用 jQuery 的 ajax 方法将图像作为 blob 检索

Bootstrap 4 文件输入

在Javascript中判断isEmpty?

jQuery确定匹配的类是否具有给定的ID

在 jQuery 中 Select 后代元素的最快方法是什么?

请求的资源错误中不存在Access-Control-Allow-Origin标头

如何禁用由子元素触发的 mouseout 事件?

jQuery中的wait()或sleep()函数?