demo:spa
1 var ar=[1,5,9]; 2 ar.name="Jon";
var sum=0;
首先用 for循環遍歷:code
1 for(var i=0;ar[i]!=null;i++){ 2 console.log(ar[i]); 3 console.log(typeof(ar[i])); 4 sum+=ar[i]; 5 } 6 console.log(sum);
輸出:對象
1,number,5,number,9,number,15blog
用for ...in遍歷:string
for(var i in ar){ console.log(ar[i]); console.log(typeof(i)); sum+=ar[i]; } console.log(sum);
輸出:1,string,5,string,9,stringr,Jon,string,15Jon console
由此能夠來對比出, for..in循環會打印出自定義屬性,下標爲string類型 ,for...in適合遍歷對象。而for循環會跳過自定義屬性的值for循環