Create JSON data directly in JS and iterate through it

  • 2020-03-30 03:35:39
  • OfStack

I've already talked about returning json data from the console to the foreground, and walking through the json data in the foreground.

Here we are going to create JSON data directly in JS and then iterate through it using ~

The creation code is as follows :(creating a JSON object)


var YearSelect = {}; 
var Year = 2014; 
var DateOption; 
for (var i = Year; i < Year + 12; i++) { 
DateOption = {'Year':i, 'Month':i-Year+1}; 
/ alert(DateOption.Year) 
YearSelect[i] = DateOption; 
}

Here you create a JSON object that contains the year and month data.

The reason I created the JSON object is because I'm familiar with JSON objects. PHP also returns a json object in the background.

Json objects do not have a length attribute ~~

So for traversal:


for(var key in YearSelect){ 
alert(YearSelect[key].Year); 
alert(YearSelect[key].Month); 
}

That's it

Remember must distinguish good json objects and arrays ~ or you've been undenfined


Related articles: