Javascript foreach for JSON 数组,语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7662997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:06:30  来源:igfitidea点击:

foreach for JSON array , syntax

javascriptjqueryjson

提问by David

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

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

result = jQuery.parseJSON(result);

now I want to check each variable of the array.

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

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

Is there any better way to make it quick like in php 'foreach' , 'while' or smth ?

有没有更好的方法让它像在 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 ?

这段代码(感谢 hvgotcodes)为我提供了数组中变量的值,但我怎样才能获得变量的名称呢?

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

UPDATE 2

更新 2

This is how php side works

这就是 php 端的工作方式

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

回答by hvgotcodes

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

它遍历返回的 json 中的所有键并打印值。但是,如果您有嵌套结构,则需要使用

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.

以确定是否必须遍历嵌套对象。我使用过的大多数 API,开发人员都知道返回内容的结构,所以这是不必要的。但是,我认为这种期望可能不适用于所有情况。

回答by Hari Pachuveetil

Try this:

尝试这个:

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

回答by Tamzin Blake

Sure, you can use JS's foreach.

当然,你可以使用 JS 的 foreach。

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

回答by yogihosting

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

您可以使用 JavaScript 的 .forEach() 方法循环 JSON。

var datesBooking = [
    {"date": "04\/24\/2018"},
      {"date": "04\/25\/2018"}
    ];
    
    datesBooking.forEach(function(data, index) {
      console.log(data);
    });