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]+'!');
} 

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