下面說一下for… in語句。可直接把下面的代碼復制到瀏覽器的控制台或Node環境下去執行。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//用來快速迭代對象。
var o ={name:'dylan',age:24,num:110}; for(var test in o){ console.log("o["+test+"]= "+o[test]); } console.log("~~~~~~~~~~~") Object.prototype.getName =function(){return this.name}; o.getAge=function(){returnthis.age};
for(var test in o){ console.log("o["+test+"]= "+o[test]); } console.log(o.getName()+o.getAge());
//getName並不是o的方法,它是Object原型方法,而Object原型方法會被
//所有Object類型實例對象所繼承的.
//因此可以看出使用for...in語句不僅能迭代出對象的屬性,還可迭代出其原型方法。
console.log("~~~~hasOwnPyroperty~~~~~~~");
for(var test in o){
if(o.hasOwnProperty(test)){
console.log("o["+test+"]= "+o[test]);
}
}
//通過調用hasOwnProperty方法過濾原型中的方法。
//如果o有二個undefined和null屬性呢?.
o.undefined ='undefined'; o.null = 'null'; console.log(o); console.log(o.toString()); console.log(o.valueOf());
for(var test in o){ if(o.hasOwnProperty(test)){ console.log("o["+test+"]= "+o[test]); } }
//如果 o=null;
o=undefined; //o=null; for(var test in o){ if(o.hasOwnProperty(test)){ console.log("o["+test+"]= "+o[test]); } }
//既不會報錯,也不會輸出。但如果是在低版本瀏覽器,很有可能報異常。因此在使用
//for-in之前,可以先過濾一下迭代對象是否為null或undefined.
console.log("~~~~Iteratearray~~~~~~~");
//迭代數組可以嗎?
var a = [26,'hellworld',newDate()]; for(var pro in a){ console.log("a["+pro+"]="+a[pro]); }
//Array也是一種對象,因此原型的getName方法同樣被迭代出來。
function keys(obj){ var aRaa = []; var i=0; for(aRaa[i++] in obj); return aRaa; } console.log(keys(o)); a.index = a.length; console.log(a); console.log(keys(a));
//當你以為是對象數組時,執行下面一條語句,發現又會發錯。
//console.log(a[index]); //報錯,index未定義
//但是下面這條語句不會報錯。
console.log(a.index);
console.log(a[getName]);
//當迭代數組時,盡量少用for....in 語句,這樣可以減少不必要的錯誤。用下面的常用方法,更好!
for(var i=0,lenght =a.length;i<lenght;i++){ console.log(a[i]); };
【Dylan童鞋】
關注Dylan童鞋,請搜索微信號:DylanTongXue 。
推送時間為:周一,周三,周四,周日晚上9:20分左右。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
查看歷史記錄請回復1~9之間的數字。比如查看第六篇文章直接回復數字:6 。顯示本幫助菜單,回復"H"。
