article source: Baidu LibraryHow does JavaScript get the array length (i.e. the number of elements in the array)? How does JavaScript get the number of members of an object? You must have thought of array.length!? So let's test the following example.
<script type= "Text/javascript" >
var a = [];
A[50] = 50;
alert (a.length);
</script>
How many elements does array a have, or in other words, what is the length of array a?
You will tell me the length is 1, but the browser will tell you that A.length is 51. What's the point? Then let's look at another example.
<script type= "Text/javascript" >
var a = [];
A[' age '] = ' 18 ';
a[' sex '] = ' Male ';
a[' site ' = ' http://www.qSyz.net ';
alert (a.length);
</script>
How many elements of array A, or in other words, what is the length of array a? We all know that the number of elements in array A is now 3, but the browser will tell you that A.length is 0!! JS How to get the number of members of an object? With the Length property?
<script type= "Text/javascript" >
var a = {' age ': +, ' sex ': ' Male '};
alert (a.length);
</script>
The above code to get the result for undefined! to sum up, length is not reliable, want to accurately get the number of JS array elements or the number of members of the object, we need to write a function ourselves. If an array is passed in, the array length is computed, and if the incoming object evaluates the number of object members, If the string is passed in, the word count of the string is computed. Other types return False
<script type= "Text/javascript" >
function Count (o) {
var t = typeof O;
if (t = = ' string ') {
return o.length;
}else if (t = = ' object ') {
var n = 0;
for (var i in O) {
n++;
}
return n;
}
return false;
}
</script>
Are you testing the example just now?
<script type= "Text/javascript" >
var a = [];
A[50] = 50;
Alert (count (a));
</script>
Get the result 2
<script type= "Text/javascript" >
var a = [];
A[' age '] = ' 18 ';
a[' sex '] = ' Male ';
a[' site ' = ' http://www.qSyz.net ';
Alert (count (a));
</script>
The results are 3.
<script type= "Text/javascript" >
var a = {' age ': +, ' sex ': ' Male '};
Alert (count (a));
</script>
Get the result 2
JS get array length, object member number, character string word