Home >Web Front-end >JS Tutorial >How to add json data to js array and the difference between js array and json_javascript skills
JSON (JavaScript Object Notation) is a lightweight data exchange format that uses a completely language-independent text format. JSON is a JavaScript native data format.
The following will introduce two ways to add json data to js arrays.
// The first way
personInfo : [], for(var i = 0; i < _STAGE.passengerInfoArray.length; i++){ var name = _STAGE.passengerInfoArray[i]; var person = {v:name, text:name}; this.personInfo.push(person); }
// The second way
var passengerInfo = {}; passengerInfo.psgTypeDesc = psgTypeDesc; passengerInfo.flightPrice = flightPrice; _STAGE.passengerInfoArray.push(passengerInfo);
The difference between js array and json
1, array
1. Define one-dimensional array: var s1=new Array();
s1=[1,2,3,4] or s1[0]=1,s1[1]=2,s1[3]=3,s1[4]=4;
alert(s1[0]);
The result is 1;
2. Define the two-dimensional element group: var s1=new Array();
var s1=[[3,1],[2,3,4],3,[4,5,6,7,8]];
alert(s1[1][0]);
The result is 2;
2. Define json object
1, json object
var status_process = { " name5" : '闲置期', "name1" : '播种期', "name2" : '苗期', "name3" : '生长期', "name4" : '采收期' } alert(status_process);
The result is: Object:Object;
2, json string
The so-called json string means that the value of the string variable has the same format as json, but is not a json object, such as:
var s1="{"; var s2 = " 'name5' : '闲置期', 'name1' : '播种期','name2' : '苗期','name3' : '生长期','name4' : '采收期'"; var s3="}"; var status_process=s1+s2 +s3;
Although the value of status_process conforms to the format of a json object, it is not an object, it is just a string (pieced together);
Convert the string to a json object using the function eval, eval("(" status_process ")");
Conclusion: What is passed from the background to the foreground is a json string, not a real json object, so it needs to be converted using the eval function.
3. Use of json objects
var status_process = { name5 : '闲置期', name1 : '播种期', name2 : '苗期', name3 : '生长期', name4 : '采收期' }; alert(status_process["name5"]); alert(status_process.name5);
Both are: idle period
4.json two-dimensional object
var status_process = { name5 : {name3:'空闲闲置期'}, name1 : '播种期', name2 : '苗期', name3 : '生长期', name4 : '采收期' }; alert(status_process["name5"]["name3"]); alert(status_process.name5.name3);
The results are: 'Idle idle period'