Home > Web Front-end > JS Tutorial > body text

How to get the instance of array length in Json array in JS

黄舟
Release: 2017-10-31 10:11:37
Original
3019 people have browsed it

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++;
 }
Copy after login

Write this code as a Method, just call it later:

function getJsonLength(jsonData){    
var jsonLength = 0;    
for(var item in jsonData){
       jsonLength++;
    }    
    return jsonLength;
}
Copy after login

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);  
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!