AI智能
改变未来

JavaScript | 语法(重点ForIn遍历)


一、if语句

[code]<html><head><meta charset=\"UTF-8\" /><title></title></head><body></body><script>score=90;if(score>=90){alert(\'A\');}else if(score>=60){alert(\'B\');}else{alert(\'C\');}</script></html>

if-elseif-else特点:

1.条件必须成立

2.只能命中其一

二、switch语句

[code]<html><head><meta charset=\"UTF-8\" /><title></title></head><body></body><script>week=45;switch(week){case 1: alert(\'Monday\');  break;case 2: alert(\'Tuesday\'); break;case 3: alert(\'Wednesday\'); break;case 4: alert(\'Thursday\'); break;case 5: alert(\'Friday\'); break;case 6: alert(\'Saturday\'); break;case 7: alert(\'Sunday\'); break;default: alert(\'NOT FOUND\'); break;}</script></html>

三、while循环

[code]<html><head><meta charset=\"UTF-8\" /><title></title></head><body></body><script>i=0;while(i<10){document.write(\'<h1>\'+i+\'<h1>\');i++;}</script></html>

四、for循环

[code]<html><head><meta charset=\"UTF-8\" /><title></title></head><body></body><script>for(i=0;i<3;i++){document.write(\'<h1>\'+i+\'<h1>\');}</script></html>

五、forIn遍历

[code]<html><head><meta charset=\"UTF-8\" /><title></title></head><body></body><script>obj={\'username\':\'user\',\'age\':\'20\',\'sex\':\'female\'};for(i in obj){document.write(\'<h1>\'+i+\': \'+obj[i]+\'</h1>\');}</script></html>

实例:九九乘法表

[code]<html><head><meta charset=\"UTF-8\" /><title></title></head><body></body><script>for(i=1;i<=9;i++){document.write(\'<h3>\');for(j=1;j<=i;j++){a=i*j;document.write(\'<span>\'+j+\'x\'+i+\'=\'+a+\'</span> \');}document.write(\'</h3>\');}</script></html>

拓展:n*n乘法表

 

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » JavaScript | 语法(重点ForIn遍历)