var n = {1:100, 2:101, 3:102, 4:103};
怎么獲取這個對象n的長度呢?
方法一:
function getLength(obj){
var count = 0;
for(var i in n){
count++;
}
return count;
}
//改進 加上一個hasOwnProperty判斷過濾下原型中的屬性就比較安全了
function getLength(obj){
var count = 0;
for(var i in n){
if(n.hasOwnProperty(i)){
count++;
}
}
return count;
}
方法二: //無需考慮hasOwnProperty的情況下
function getLength(obj){
return Object.key(n).length;
}