JS循环语句

一、for循环

//双循环
for (var i = 0; i < 5; i++) {
		for (var j = 0; j < 5; j++){
			console.log(i+','+j);
		}
	}

在这里插入图片描述

二、for in循环

  • 示例一:
var arr=[1,2,3];
	for (var i in arr) {
		console.log(i);
		console.log(arr[i]);
		console.log(i,arr[i]);
	}

在这里插入图片描述

  • 示例二:
var json={
		'name':'leo',
		'age':'18',
		'height':'180'
	}

	for(var i in json){
		console.log(i);
		console.log(json[i]);
		console.log(i+','+json[i]);
	}

在这里插入图片描述

三、while循环

  • 示例一:
var i=0;
	while(i<10){
		console.log(i);
		i++;
	}

在这里插入图片描述

  • 示例二:
	var i=0;
	var j=0;
	while(i<3){
			while(j<3){
				console.log(i+','+j);
				j++;
			}
		i++;
	}

里面循环完了就不管了,只循环一次

在这里插入图片描述

四、do while循环

var i=0;
	do{
		console.log(i);
		i++;
	}
	while(false);//do while最低执行一次

五、forEach

//forEach 数组
// 数组.forEach(function(e){
// 	alert(e)
// })
// 数组的内容一个一个走
  • Tips:for、while、do while不能互相穿插

六、综合

//for循环
ipt1.onclick=function(){
	for (var i=0; i < allDiv.length; i++) {
				allDiv[i].style.background='red';
			}
}

//for in循环
ipt2.onclick=function(){
	var arr=[];
	for (var i=0; i < allDiv.length; i++) {
				arr.push(allDiv[i]);
			}
    for (var i in arr) {
    	allDiv[i].style.background='red';
    }
}

//while循环
ipt3.onclick=function(){
	var i=0;
	while(i<allDiv.length){
		allDiv[i].style.background='red';
		i++;
	}
}

//do while循环
ipt4.onclick=function(){
	var i=0;
	do{
	allDiv[i].style.background='red';
		i++;
	}
	while(i<allDiv.length)
	}

//for each循环
ipt5.onclick=function(){
				var a=[allDiv[0],allDiv[1],allDiv[2],allDiv[3],allDiv[4]];
				a.forEach(function(x){
					x.style.backgroundColor='red'
				})
			}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值