第三章(4):基本概念(学习笔记)

语句

ECMAScript中的语句和大多数编程语言的语句类似。

  • if 语句
if(...) {
...
} else {
...
}
  • do-while 语句
    先执行后判断,最少执行一次。tips:在工作中我还没用过- -!
do {
...
} while(...)
  • while 语句
    先判断后执行。
while(...) {
...
}
  • for 语句
    循环语句。
for(var i = 0; i < 10; i++) {
  console.log(i)
}
  • for-in 语句
    用来枚举对象的属性。顺序在不同的浏览器中可能不一致。
for(name in obj) {
  ...
}
  • break和continue语句
    break是跳出循环,continue是跳过本次循环
  let i = 0
  let iCount = 0
  for(i; i < 10; i++) {
    if(i === 5) {
        break;
    }
    iCount++
  }
  console.log(`iCount: ${iCount}`)  // 5

  let j = 0
  let jCount = 0
  for(j; j < 10; j++) {
      if(j === 5) {
          continue;
      }
      jCount++
  }
  console.log(`jCount: ${jCount}`)  // 9
  • with 语句
    /**
   *  将代码的作用域设置到一个特定的对象中。
   *  如果with作用域中的变量找不到,就挂在location中。
     */
    with (location) {
    console.log(href) // location.href
    console.log(host) // location.host
    console.log(cc);  // Uncaught ReferenceError: cc is not defined
  }
  • switch 语句
    流程控制语句。
switch(...) {
  case ...:
    ...
    break;
default:
  ...
}

另外一种妙用。

switch(true) {
  case x < 10:
    console.log(x)
    break;
  case x < 20:
    console.log(x)
    break;
...
}

函数

通过function 来声明函数。

function test() {
...
}
  • 参数传递
    不在乎传递参数的数量和类型。在函数体内可以通过arguments来获取参数。arguments是一个类数组。
    /**
   * arguments
     */
    function args() {
    if(arguments.length === 1) {
        console.log('1个参数:', arguments[0])  
    } else {
        console.log('2个参数:', arguments[0] + arguments[1])
    }
  }

  args(1) // 1
  args(1, 2)  // 3

引用

javascript 高级程序设计

你可能感兴趣的:(第三章(4):基本概念(学习笔记))