js中for循环与for in的区别

在javascript中我们通常用的for,for in方法总感觉没什么区别,但是在一次的学习的过程中我发现了for与for in还真有点区别。接下来让我们简单的区分一下:

首先先看一下for的语法的结构以及他的写法
for(初始值,判断条件,步长值){

};

for(i=0;i<10;i++){
console.log(i) //0 1 2 3 4 5 6 7 8 9 
};

for in是用来遍历来用的

data={
    x:["一月","二月","三月","四月","五月","六月"],
    y:["0","100","200","300","400","500","600","700","800","900","1000"],
    val:["300","210","120","560","800","660"],
    col:["red","green","blue","skyblue","orange","pink"]
    }
for(var i in  data.x/y/val/col){
console.log(data.x[i])//会打印出data对象里x的每一项,["一月","二月","三月","四月","五月","六月"]
}
var data = {//data只是个变量名
  age:20,
  name:"小李子",
  xingbie:"男"
}
for(var i in data){
  console.log(i);//  输出的是 k值:age  name  sex
  console.log(wq[attr]);//属性相对应的value值  20  小李子  男
}

两者一对比就大致可以看出for in遍历对象是最适合了,如果用for的话,对象里面的k值和value值只好无能为力,那就只能用for in。如果只是普通的数组,用for最适合;那如果for in遍历普通数组话,他会自带length属性,到后面会报错,所以for in不适合循环遍历普通数组。

你可能感兴趣的:(js中for循环与for in的区别)