for 循环 和for..in循环遍历数组 的区别
demo:
1 var ar=[1,5,9]; 2 ar.name="Jon";
var sum=0;
首先用 for循环遍历:
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,15
用for ...in遍历:
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
由此可以来对比出, for..in循环会打印出自定义属性,下标为string类型 ,for...in适合遍历对象。而for循环会跳过自定义属性的值