先端基本JSフロー制御文(4)
15507 ワード
forサイクル
<html lang="en">
<head>
<meta charset="UTF-8">
<title>fortitle>
<style>
body{text-align:left;}
style>
head>
<body>
<script>
// 1-100 101 1 2 3 4
// //
for(var i=1;i<=100;i++){
document.write(i+'
'); // 1 2 3 100
}
// 99 97 95 ...3 1
for(var m=99;m>=1;m-=2){
console.log(m); // 99 97 3 1
}
//alert(m); // -1
script>
body>
html>
ループネスト for(var i=1;i<=9;i++){
// i=1; j<=1; i=2;
for(var j=1;j<=i;j++){
document.write(j+'*'+i+'='+j*i+' ');
// 1*1=1 1*1=1 2*2=4
}
document.write('
');
}
分岐文
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
<script>
/*var age=35;
if(age<18){
alert(" ");
}
var age=prompt(" ");
/*if(age<18){
alert(" ");
}else{
alert(" , ");
}
if(age.length!=6){
alert(" 6 ");
}else{
if(isNaN(age)){
alert(" 6 ");
}else{
alert(" ");
}
}*/
var score=prompt(" ");
var result="";
if(isNaN(score)){
alert(" ");
}else{
if(score<0 || score>100){
alert(" ");
}else{
switch(parseInt(score/10)){
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
result=" ";
break;
case 6:
result=" ";
break;
case 7:
result=" ";
break;
case 8:
result=" ";
break;
case 9:
result=" ";
break;
default:
result=" "
}
alert(" :"+result);
}
}
script>
body>
html>
while
<html lang="en">
<head>
<meta charset="UTF-8">
<title>whiletitle>
head>
<body>
<script>
var i=1;
while(i<=100){
document.write(i+'
'); // 1 2 100
i+=1; // i++
}
//1 - 10
/* var j=18;
do{
if(j%2==0){
console.log(j);
}
j++;
}while(j<=10);
*/
// 1+2+3+4+...100=?
// sum=0+1=1
// sum=0+1+2
// sum=0+1+2+3
// sum=0+1+2+3+4
var sum=0; // sum
var n=1;
while(n<=100){
sum+=n; // sum=sum+n; // sum=0+1; sum=0+1+2+3+100
n++;
}
console.log(sum);
script>
body>
html>
スイッチ
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
<script>
for(var i=0,col="";i<=100;i++){
switch(i%4){
case 0:
col="red";
break;
case 1:
col="green";
break;
case 2:
col="blue";
break;
default:
col="orange";
}
document.write(''">'+i+'
');
}
script>
body>
html>
contine&break
<html lang="en">
<head>
<meta charset="UTF-8">
<title>break continuetitle>
head>
<body>
<script>
var num=0;
for(var i=1;i<10;i++){
// i 5 ,
if(i%5==0){
break;
}
num++; // i=1,num=1;i=2,num=2;i=3,num=3,i=4,num=4,i=6,num=5
}
//console.log(num);
for(var s=0,j=1;j<=10;j++){
if(j%5==0){
continue;
}
s+=j;
// j=1,s=1;j=2,s=3;j=3,s=6;j=4,s=10,j=5,s=10;j=6,s=16,j=7,s=23;j=8,s=31;j=9,s=40,j=10
}
//console.log(s);
// 0-50 20 30 5
for(var n=0;n<=50;n+=5){
if(n==20 || n==30){
continue;
}
console.log(n);
}
script>
body>
html>