js獲取陣列元素個數和物件成員數
阿新 • • 發佈:2019-02-05
Javascript怎麼獲取物件的成員個數?
你肯定想到了array.length!? 那麼我們來測試一下下面這個例子.
-
<script type="text/javascript">
-
var a = [];
-
a[50] = 50;
-
alert(a.length);
- </script>
有點意思吧? 那我們再看一個例子.
-
<script type="text/javascript">
-
var a = [];
-
a['age'] = '18';
-
a['sex'] = 'Male';
-
a['site'] = 'http://www.qSyz.net';
-
alert(a.length);
- </script>
我們都知道現在陣列a的元素個數為3個,但瀏覽器會告訴你a.length為0 !!
js怎麼獲取物件的成員個數? 用length屬性嗎?
-
<script type="text/javascript">
-
var a = {'age':30,'sex':'male'};
-
alert(a.length);
- </script>
綜上所述,length不可靠,要想得到準確的陣列元素個數或者物件的成員個數,我們需要自己動手寫一個函式.
如果傳入陣列則計算陣列長度,如果傳入物件則計算物件成員數,如果傳入字串則計算字串的字數.其他型別返回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>
-
<script type="text/javascript">
-
var a = [];
-
a[50] = 50;
-
alert(count(a));
- </script>
-
<script type="text/javascript">
-
var a = [];
-
a['age'] = '18';
-
a['sex'] = 'Male';
-
a['site'] = 'http://www.qSyz.net';
-
alert(count(a));
- </script>
-
<script type="text/javascript">
-
var a = {'age':30,'sex':'male'};
-
alert(count(a));
- </script>