For…In 聲明用于遍歷數組或者對象的屬性(對數組或者對象的屬性進行循環操作)。
先定義一個構造函數:
var Status = function(arg){ this.arg = arg;}Status.prototype.getStatus = function(){ return this.arg;}
接著實例化:
var instance = new Status('a test string');instance.getStatus();instance.ooxx = 'ooxx';
用 for…in 遍歷屬性:
for(i in instance){ console.log(i);}
看下運行結果:
argooxxgetStatus
可見原型方法也被遍歷出來的,但事實上往往并不想要。于是需要這么干:
for(i in object){ if(object.hasOwenProperty(i)){ //... }}
這樣就能把函數和原型屬性方法過濾掉鳥~