在javascript中我們通常用的for重斑,for in方法總感覺沒什么區(qū)別,但是在一次的學(xué)習(xí)的過程中我發(fā)現(xiàn)了for與for in還真有點(diǎn)區(qū)別值依。接下來讓我們簡單的區(qū)分一下:
首先先看一下for的語法的結(jié)構(gòu)以及他的寫法
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的每一項(xiàng)颇蜡,["一月","二月","三月","四月","五月","六月"]
}
var data = {//data只是個變量名
age:20,
name:"小李子",
xingbie:"男"
}
for(var i in data){
console.log(i);// 輸出的是 k值:age name sex
console.log(wq[attr]);//屬性相對應(yīng)的value值 20 小李子 男
}
兩者一對比就大致可以看出for in遍歷對象是最適合了,如果用for的話辆亏,對象里面的k值和value值只好無能為力风秤,那就只能用for in。如果只是普通的數(shù)組扮叨,用for最適合缤弦;那如果for in遍歷普通數(shù)組話,他會自帶length屬性彻磁,到后面會報錯碍沐,所以for in不適合循環(huán)遍歷普通數(shù)組狸捅。