天行健,君子以自强不息;地势坤,君子以厚德载物。
每个人都有惰性,但不断学习是好好生活的根本,共勉!
文章均为学习整理笔记,分享记录为主,如有错误请指正,共同学习进步。
山明月露白,夜静松风歇。
文章目录
- JavaScript的选择结构和循环结构
- 1. 选择结构
- 1.1 if...else
- 1.2 switch
- 2. 循环结构
- 2.1 while
- 2.2 do...while
- 2.3 for
- 2.4 for...in...
- 3. 示例代码下载
JavaScript的选择结构和循环结构
1. 选择结构
JS中选择结构有if…else和switch
1.1 if…else
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>选择结构-if-else</title>
<script>
var id = 1;
if(id>0){
console.log("id为正数");
}else if(id<0){
console.log("id为负数");
}else{
console.log("id为0");
}
</script>
</head>
<body>
</body>
</html>
浏览器控制台打印结果
1.2 switch
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>选择结构-switch</title>
<script>
var id = "1";
switch(id){
case "1":
console.log("libai");
break;
case "2":
console.log("baijuyi");
break;
case "3":
console.log("menghaoran");
break;
default:
console.log("liqingzhao");
break;
}
</script>
</head>
<body>
</body>
</html>
浏览器控制台打印结果
2. 循环结构
循环结构有while,do…while,for,for…in
2.1 while
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>循环结构-while</title>
<script>
var id = 1;
while(id<10){
console.log("循环加1",id);
id++;
}
console.log("此时id值不满足id<10,跳出循环,id:",id);
</script>
</head>
<body>
</body>
</html>
浏览器控制台打印结果
2.2 do…while
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>循环结构-do-while</title>
<script>
var id = 1;
do{
console.log("循环加1",id);
id++;
}while(id<10);
console.log("此时id值不满足id<10,跳出循环,id:",id);
</script>
</head>
<body>
</body>
</html>
浏览器控制台打印结果
2.3 for
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>循环结构-for</title>
<script>
var sum = 0;
for(var i=1; i<10; i++){
console.log("i:",i);
sum+=i;
}
console.log("1-9数字累加的和为sum:", sum);
</script>
</head>
<body>
</body>
</html>
浏览器控制台打印结果
2.4 for…in…
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>循环结构-增强for循环-for-in</title>
<script>
var str = "libai";
//迭代
for(var index in str){
console.log("index:",index);
console.log("str[index]:",str[index]);
}
</script>
</head>
<body>
</body>
</html>
浏览器控制台打印结果
3. 示例代码下载
示例代码已上传至CSDN资源库
下载地址:JavaScript 选择结构和循环结构 示例代码
感谢阅读,祝君暴富!