day15
javaScript条件语句
分支语句
条件语句
if语句基本用法
语法一:
if(condition){
statement1;
}
alert()
语法:alert()
功能:弹出警告对话框
语法二:
if(condition){
statement1;
}else{
statement2;
}
prompt()
语法:prompt()
功能:弹出输入框
返回值:
1.点击确定,返回输入内容
2.点击取消,返回null
语法三:
if(condition){
statement1;
}else if(){
statement2;
}....
else{
statement3;
}
length
语法:string.length
功能:获取string字符串的长度
返回值:number
获取星期
语法:new Date().getDay()
功能:获取星期
返回值:number(0-6)
switch语句
语法:
switch(expression){
case value:statement
break;
case value:statement
break;
....
default:statement
}
输出:
语法:document.write("内容")
功能:向浏览器输出内容
Javascript循环语句
for for-in while do-while
for语句
语法:
for(语句1;语句2;语句3){
被执行的代码块;
}
嵌套
当循环与循环发生嵌套式遵循下列规则:
1,外层为假时内层不执行;
2,先执行外层再执行内层,直至内层的条件为假时再返回外层去执行。
while语句
语法:
while(条件){
需要执行的代码;
}
do-while语句
语法:
do{
需要执行的代码;
}while(条件)
说明:这个语法的循环至少要被执行一次
for与while的区别
for 适合一直循环次数的循环体
while 适合未知循环次数的循环体
break语句
break:立即退出循环
continue语句
continue:结束本次循环,继续开始下一次。
if综合案例.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>if综合案例</title> </head> <body> <script> var password = prompt("请输入6位密码"); if (password.length !=6) { alert("不是六位数字"); } else { if (isNaN(password)) { alert("请输入6位数字!"); } else { alert("密码已保存"); } } </script> </body> </html>
switch.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>switch</title> </head> <body> <script> var week = new Date().getDay(); var weekstr = ""; switch(week){ case 0: weekstr = "日"; break; case 1: weekstr = "一"; break; case 2: weekstr = "二"; break; case 3: weekstr = "三"; break; case 4: weekstr = "四"; break; case 5: weekstr = "五"; break; default: weekstr = "六"; } document.write("今天是星期"+weekstr); </script> </body> </html>
for.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>for</title> </head> <body> <!-- <script> for (var i = 1; i < 101; i++) { document.write(i+"<br>") } </script> --> <!-- 循环嵌套 --> <script> for (var i = 1; i < 4; i++) { document.write(i+'<br>'); document.write('<hr>') for (var m = 1; m < 6; m++) { document.write(m+"<br>") } }</script> </body> </html>
while.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>while</title> </head> <body> <script> var i = 1; /*while(i<101){ document.write(i+'<br>'); i++; }*/ /* do{ document.write(i+'<br>'); i++; }while(i<101)*/ var sum = 0; var n = 0; while(n<100){ n++; console.log(n); sum+=n; } console.log(sum); </script> </body> </html>
break_continue.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>break_cotinue</title> </head> <body> <script> /*var num = 0; for (var i = 1; i < 10; i++) { if (i%5 == 0) { // break; continue; } num++; } console.log(num);*/ //打印所有0-50之间除20和30之外的5的倍数 for (var i = 0; i < 51; i+=5) { if(i == 20 || i==30) continue; console.log(i); } </script> </body> </html>