js语句

js语句分为:条件语句,循环语句,with语句,异常捕获语句;

1 条件语句

1.1 if语句

/* if(条件){语句1}else{语句2} */
var isMale = false;
if(isMale){
    document.write('male');
}else{
    document.write('female');
}
//female

/* if(条件1){语句1}else if(条件2){语句2}else{语句3} */
var score = 65;
if(score > 70){
    document.write('A');
}else if(score >=60){
    document.write('B');
}else{
    document.write('C');
}
//B

1.2 switch语句

/* switch(表达式){case值1:result1;break;case值2:result2;break;default:result3} */
var degree = 'B';
switch(degree){
    case'A':
        document.write('Excilent');
        break;
    case'B':
        document.write('good');
        break;
    default:
        document.write('need more effort');
    }
    //good

2 循环语句

2.1 while语句

/* while(表达式){语句} */
var i = 1;
while(i<=10){
    document.write(i);
    i++;
}
//12345678910

/* do{语句}while(表达式) */
var i = 11;
do{
    document.write(i);
    i++;
}
while(i<=10)
//11,经过实验结果应该为12345678910,到不了11

2.2 for循环

/* for(初始化;循环条件;更新表达式){语句} */
for(var i = 1;i<=10;i++){
    document.write(i);
}
//这个for循环和前面while循环的结果是一样的:12345678910
/* 在for循环中还有两个关键词:`break`和`continue`,用法如下 */
for(var i=1;i<=10;i++){
    if(i == 5){break;}
    document.write(i);
}
//1234
for(var i=1;i<=10;i++){
    if(i ==5){continue;}//这里if语句和document语句的顺序会影响结果的输出,要注意!
    document.write(i);
}
//1234678910

2.3 for-in循环

/* for(属性名 in 对象){语句} */
---
var cat = {
    neme:'kitty',
    age:2,
    mew:function(){
        console.log('miao miao miao');
    }
}
---
for(var p in cat){
    document.write(p);
}
//name age mew

2.4 for-of循环遍历

一种用于遍历数据结构的方法。它可遍历的对象包括数组,对象,字符串,set和map结构等具有iterator接口的数据结构。

var arr = [1,2,3,4,5];

for(let i=0;i<arr.length;i++){};//经典但不够简洁
arr.forEach(function(value,index){});//无法中断整个循环
for(let o in arr){
    document.write(o);//0 1 2 3 4
};//适用于对象的循环,处理数组需要转换i

for(let value of arr){
    console.log(value);//1 2 3 4 5
}

//循环可以终止、跳出
for(let value of arr){
    if(value == 3){
        break;
    }
    console.log(value);//1 2
}
for(let value of arr){
    if(value == 3){
        continue;
    }
    console.log(value);//1 2 4 5
}
//得到数字类型的索引
for(let index of arr.keys()){
    console.log(index);//0 1 2 3 4
}
//遍历字符串
let word = 'nihaoya';
for(let w of word){
    console.log(w);//n i h a o y a
}
//数组
let plist = document.getElementsByTagName('p');
for(let p of plist){
    console.log(p);//<p>1</p> <p>2</p> <p>3</p>
}

3 with语句

var kitty = {
    age:3,
    friend:{
        neme:'snoopy',
        age:2
    }
}
---
document.write(kitty.friend.name +'\'s age is' +kitty.friend.age);
//snoopyk's age is2
---

/* with(表达式){语句} */
with(kitty.friend){
    document.write(name +'\'s age is' +age);
}

4 异常捕获语句

/* try{语句}catch(exception){语句}finally{语句} */
try{
    document.write(notDefined);
}catch(error){
    alert(error);
}finally{
    alert('finally');
}
//ReferenceError:...
//finally
posted @ 2021-01-14 21:56  格一  阅读(104)  评论(0)    收藏  举报