foreach for JSON array , syntax

前端 未结 4 609
夕颜
夕颜 2021-01-30 12:34

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.

相关标签:
4条回答
  • 2021-01-30 12:55

    Try this:

    $.each(result,function(index, value){
        console.log('My array has at position ' + index + ', this value: ' + value);
    });
    
    0 讨论(0)
  • 2021-01-30 12:59

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

    0 讨论(0)
  • 2021-01-30 13:02

    Sure, you can use JS's foreach.

    for (var k in result) {
      something(result[k])
    }
    
    0 讨论(0)
  • 2021-01-30 13:22

    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.

    0 讨论(0)
提交回复
热议问题