JavaScript學習筆記(循環)

在JavaScript中的循環分爲:for(for…in ),while,do…while

①for(for…in)

for

利用for循環計算1 * 2 * 3 * … * 10的結果:

var x = 1;
var i;
for (i=1; i<=10; i++) {
    x = x * i;
}
if (x === 3628800) {
    console.log('1 x 2 x 3 x ... x 10 = ' + x);
}
else {
    console.log('計算錯誤');
}

結果:

1 x 2 x 3 x ... x 10 = 3628800

for循環最常用的是利用索引來遍歷數組:

var arr = ['Apple', 'Google', 'Microsoft'];
var i,x;
for (i = 0; i < arr.length; i++) {
	x = arr[i];
	console.log(x);
}

for…in

for…in循環,可以把一個對象中的所有屬性依次循環出來

var jb = {
	name:'hk',
	age:18,
	hobby:'籃球'
};
for(var Key in jb){
	console.log(Key);
}


可以通過hasOwnProperty()來過渡掉對象繼承的屬性

var jb = {
	name:'hk',
	age:18,
	hobby:'籃球'
};
for(varKey in jb){
	if(jb.hasOwnProperty(Key)){
		console.log(Key);
	}
}

②while

條件滿足就不斷的循環,條件不滿足就退出循環,例如:

var x = 0;
var n = 99;
while(n > 0){
	x = x + n;
	n = n-2;
}
console.log(x);

③do…while

在每次循環開始前,不用先判斷條件,而是先執行後判斷 條件如果滿足就再執行,直到條件不滿足時,退出循環!

var n = 0;
do{
	n = n + 1;
}while(n < 100);

用do { … } while()循環要小心,循環體會至少執行1次,而for和while循環則可能一次都不執行。
小demo:
請利用循環遍歷數組中的每個名字,並顯示你好啊, xxx!:

var arr = ['hk','gg','xsb'];
var i;
for(i = 0;i<3;i++){
   console.log('hello,'+arr[i]+'!');
} 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章