1.switch分支结构
if else if else 多分支
switch跟他一样的都是多分支但是有区别
1 swich一般不进行范围内的判断
2 switch是对准确的某些值进行判断
3判断的时候要求值和类型都相等也就是三个等号===
4 switch的default可以不写
含义
switch 岔路岔道口
case 方案
break 打断的 中断
default 默认
break的含义
从满足第一个方案的case开始
如果没有break
后面的条件不在判断了
格式
switch(要判断的内容){
case 方案一:
方案一满足执行的代码
break
case 方案二:
方案二满足执行的代码
break
...
default:
上面的方案都不满足这里的代码
}
2.三元运算符
又叫三目/三元
语法是:
条件?如果条件成立选这个:条件不成立选这个
节约代码行数
执行代码
给变量赋值
age>=18?'成年':'未成年'
闰年?
var year=1002;
var test=(year%4==0&&year%100!=0||year%400==0)?28:29;
让用户输入日期,输出这个日期是第几天
<script> // 让用户输入年月日比如2022年10月20日判断这一天是这一年的第几天 // 提示判断是否是闰年如年 2月29天平年 28天 //拿到年 判断是否闰年 //拿到月 获取比它小的月份 //拿到天 用来累加 //switch 向下穿透 //if if // var year = 2020, // month = 1, // day = 1, // new_day = day; // if (month > 1) { // day += 31; // } // if (month > 2) { // day += (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 28 : 29; // } // if (month > 3) { // day += 31; // } // if (month > 4) { // day += 30; // } // if (month > 5) { // day += 31; // } // if (month > 6) { // day += 30; // } // if (month > 7) { // day += 31; // } // if (month > 8) { // day += 31; // } // if (month > 9) { // day += 30; // } // if (month > 10) { // day += 31; // } // if (month > 11) { // day += 31; // } // if (month > 12) { // day += 30; // } // console.log(year + '年' + month + '月' + new_day + '天是第' + day + '天'); var year = 2020, month = 3, day = 24 new_day = day;//仅仅打印的时候用到 switch (month) { case 12: day += 31 case 11: day += 31 case 10: day += 30 case 9: day += 31 case 8: day += 31 case 7: day += 30 case 6: day += 31//六月份加五月份的天数 case 5: day += 30//五月份加四月份的天数 case 4: day += 31//四月份加三月份的天数 case 3: day += (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 28 : 29 case 2: day += 31;//二月份加一月份的天数 case 1: day } console.log(year + '年' + month + '月' + new_day + '天是第' + day + '天');
4.while循环
设定初始值 while(条件){ 重复执行的动作 初始值要变化 } 首先进行条件的判断 如果条件为false 不进入大括号 代码不执行 如果条件为true 进入大括号 执行代码 {}内的代码执行完毕 再次进行条件的的判断 断点调试 源代码=>选中几行=>右侧监视=>输入你想监视的 比如count 就能知道count是怎么变化的了 var count=1;//初始值 while(count<=10){ // console.log('围着操场跑圈')//执行的代码 重复执行的 console.log(`围着操场跑第${count}圈`);//用反单引号解析变量 count++//count+=1 为了防止死循环 这个值要变化 }
位置不同输出的结果不同 加在num++前面
var num=0 while(num<10){ console.log(num); num++ }//0123456789 var num=0 while(num<10){ num++ console.log(num); }//123456789 10 var num=1 while(num<10){ console.log(num); num++ }//123456789 var num=1 while(num<10){ num++ console.log(num); }//23456789 10
1-100 3的倍数的和 第一种 var num=1; var sum=0; while(num<=100){ if(num%3==0){ sum+=num; } num++ } console.log(sum) 1-100 3的倍数的和 第二种 var num=3; var sum=0; while(num<100){ sum+=num // console.log(num) num+=3 } console.log(sum)
1-10以内的和 var count=1;//初始值为1 var sum=0//定义一个容器 用来存放最后的和 while(count<=10){ sum+=count count++ } console.log(sum)
5.do while
do{
}while(条件)
输密码 直到输入准确位置
前提提醒我输入密码
do{ var paw=prompt('请输入密码'); }while(paw!=='123456') console.log('欢迎光临')
6.for
for(初始值;条件;累加){ 重复执行的代码 }
1-100以内能整除5的数
for(var num=1,jishu=0;num<=100;num++){ if(num%5==0){ jishu++ num++ console.log(jishu) } }