Home > Article > Web Front-end > How to get the instance of array length in Json array in JS
As a front-end page developer dealing with json data for the first time, I encountered 'js gets the length of the array in the json array'? I didn’t even know that json doesn’t have the .lengthattribute (I really want to ridicule myself). If a young man doesn’t work hard, he will be miserable! I used to seek help from my boyfriend, but recently I try to solve the problems myself.
The problem I encountered is this: In the page at the end of ***.jsp, the json data passed to me by the backend is an array, and then I need to get the second array. The length of the array in contacts, and then Baidu discovered that json does not have a .length attribute. How to do it?
Since the jsonobject does not have a length attribute, what should I do if I want to know its length?
var jslength=0; for(var js2 in json){ jslength++; }
Write this code as a Method, just call it later:
function getJsonLength(jsonData){ var jsonLength = 0; for(var item in jsonData){ jsonLength++; } return jsonLength; }
But the above method can only get the length of the first layer array? ? ? Can't get the array length in the subarray? ? ? Then I played with myself and successfully obtained the length of the contacts array using the following method.
var _data = ${contactJson}; function getJsonLength(jsonData){ var jsonLength = 0; for(var item in jsonData){ if(item == 'contacts'){ for(var x in jsonData[item]){ jsonLength++; } } } return jsonLength; }var _contact_num = getJsonLength(_data); $('#contactNum').text(_contact_num);
The final result:
The above is the detailed content of How to get the instance of array length in Json array in JS. For more information, please follow other related articles on the PHP Chinese website!