<script type="text/javascript">
var a = [];
a[50] = 50;
alert(a.length);
</script>
请问数组a有多少个元素, 或者换一句话说, 数组a的长度为多少?
<script type="text/javascript">
var a = [];
a['age'] = '18';
a['sex'] = 'Male';
a['site'] = 'http://www.qSyz.net';
alert(a.length);
</script>
<script type="text/javascript">
var a = {'age':30,'sex':'male'};
alert(a.length);
</script>
<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>
得到结果为2
<script type="text/javascript">
var a = [];
a['age'] = '18';
a['sex'] = 'Male';
a['site'] = 'http://www.qSyz.net';
alert(count(a));
</script>
得到结果为3.
<script type="text/javascript">
var a = {'age':30,'sex':'male'};
alert(count(a));
</script>
得到结果为2