【温故知新】——原生js中常用的四种循环方式

时间:2022-11-08 15:24:06

一、引言

本文主要是利用一个例子,讲一下原生js中常用的四种循环方式的使用与区别:

实现效果:

  1. 在网页中弹出框输入0   网页输出“欢迎下次光临”
  2. 在网页中弹出框输入1   网页输出“查询中……”
  3. 在网页中弹出框输入2   网页输出“取款中……”
  4. 在网页中弹出框输入3   网页输出“转账进行中……”
  5. 在网页中弹出框输入其他字符   网页输出“无效按键”

四种循环:

  • for循环
  • while循环
  • for  in 循环
  • for  of 循环

二、for循环

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>for 循环</title>
</head>
<body>
<script>
var input=parseInt(prompt("请按键:"));
for(var i=input;i!=;i++){
if(i==1){
document.write("查询中...");
break;
}else if(i==2){
document.write("取款中...");
break;
}else if(i==3){
document.write("转账进行中...");
break;
}else{
document.write("无效按键");
}
break;
}
if(input==0){
document.write("欢迎下次光临!");
}
</script>
</body>
</html>

三、while循环

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>while 循环</title>
</head>
<body>
<script>
var input=-1;
while((input=parseInt(prompt("请按键")))!=){
if(input==1){
document.write("查询中...");
break;
}else if(input==2){
document.write("取款中...");
break;
}else if(input==3){
document.write("转账进行中...");
break;
}else{
document.write("无效按键");
}
break;
}
if(input==0){
document.write("欢迎下次光临!");
}
</script>
</body>
</html>

四、for in 循环

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>for in 循环</title>
</head>
<body>
<script>
var input=parseInt(prompt("请按键:"));
var array=new Array();
array.push(input);
for(var key in array){
if(array[key]==0){
document.write("欢迎下次光临!");
}else if(array[key]==1){
document.write("查询中...");
break;
}else if(array[key]==2){
document.write("取款中...");
break;
}else if(array[key]==3){
document.write("转账进行中...");
break;
}else{
document.write("无效按键");
}
break;
}
</script>
</body>
</html>

五、for of循环

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>for of循环</title>
</head>
<body>
<script>
var input=parseInt(prompt("请按键:"));
var array=new Array();
array.push(input);
for(var val of array){
if(val==0){
document.write("欢迎下次光临!");
}else if(val==1){
document.write("查询中...");
break;
}else if(val==2){
document.write("取款中...");
break;
}else if(val==3){
document.write("转账进行中...");
break;
}else{
document.write("无效按键");
}
break;
} </script>
</body>
</html>