1

Javascript——程序流程控制

 2 years ago
source link: https://segmentfault.com/a/1190000040774057
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
    • JS 代码从第一句代码开始往下执行,执行完上一句在执行下一句
  • 分支选择结构

    • JS 代码根据不同的条件进行判断,满足条件执行代码,不满足条件直接跳过
    • 单分支选择语句
    if(条件表达式){
      执行代码;
    }
    • 双分支选择语句
    if(条件表达式){
      执行代码;
    }
    else{
      执行代码;
    }
    • 多分支语句
    if(条件表达式){
      执行代码;
    }
    else if(条件表达式){
      执行代码;
    }
    else{
      //当 if() else if()条件都不满足时,执行else内的代码
      执行代码;
    }
    • switch 多分支语句
    switch(表达式){
      case 常量:
          执行语句;
          break;
      case 常量:
          执行语句;
          break;
      default:
          //当以上都不满足时,执行这里面代码
          //berak 表示执行完跳出switch语句,在特殊场景可省略不写
          执行语句;
          break;
    }
    • if 语句与 switch 语句的选用规则

      • 当判断的条件是一个确定的结果时,使用 switch 语句;
      • 当判断的条件不是一个确定的结果时,使用 if 语句
    • while 循环语句
    初始化条件;
    while(条件表达式){
      执行语句;
      条件调整语句;
    }
    • do while 循环语句
    初始化条件;
    do{
      执行语句;
      条件调整语句;
    }while(条件表达式);
    • while语句 与 do while语句的区别

      • do while语句无论条件是否成立,都会执行一遍代码,在进行条件判断
      • while语句会进行条件判断,在执行代码
    • for() { } 语句
    for(初始化语句; 条件表达式; 调整语句) {
      执行语句
    }
    • for语句相对于while语句、do while语句 将初始化语句、判断语句、调整语句整合在一起,结构上方便后期维护
  • 循环语句中的 break 和 continue

    • 当循环中遇到 break 时,则直接终止循环
    • 当循环中遇到 continue 时,跳过本循环,执行下一次循环
  • 循环语句的优点与注意事项:

    • 优点:循环结构可以使代码更简洁,方便后期的维护
    • 注意事项:当 判断条件 永远成立时,程序则进入死循环
    • 循环的必要条件:①初始化语句 ②条件判断语句 ③执行代码 ④调整语句
  • JS 标记语法

    here://外层的标记
    for(var i=0;i<10;i++){
      for(var j=0;j<10;j++){
          console.log('内层循环');
          if(i===5&&j===6){
              //跳出到外层的标记
              break here;
          }
      }
    }

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK