JavaScript 判断、循环语句

if

1if (i > 1)
2  alert('yes')
3else
4  alert('no')

如果只有一条可以省略 {},但容易导致错误,应该避免

1if (i > 1)
2  alert('yes')

do-while

  • 语句最少执行一次
1let i = 0
2do
3  i += 2
4while (i < 10)

while

1let i = 0
2while (i < 10)
3  i += 2

for

1let a = 0
2for (let i = 0; a < 10; i++)
3  a += 1

for in

  • 遍历数组/对象
1const arr = ['Saab', 'Volvo', 'BMW']
2
3for (const x in arr)
4  document.write(`${arr[x]}<br />`)

for of

1const arr = [
2  [1, 2],
3  ['a', 'b'],
4]
5for (const [key, value] of arr)
6  console.log(`${key},${value}`)
7
8// 1,2
9// a,b
  • break;停止循环
  • continue;停止这次循环

with

  • 改变代码块的作用域,查找变量会先找 obj 里面的
  • 大量使用 with 会导致性能下降,不建议使用(因为修改了作用域链)
1with (obj) {
2  // 代码块
3}

switch

1switch (i) {
2  case '0':
3    alert('1') // i为0时
4    break // 退出
5
6  default: // 默认执行
7    alert('default')
8}

关键字与保留字

ECMA-262 第 6 版规定的所有关键字如下:

break do in typeof case else instanceof var catch export new void class extends return while const finally super with continue for switch yield debugger function this default if throw delete import try

始终保留:enum

严格模式下保留:

implements package public interface protected static let private

模块代码中保留:await

这些词汇不能用作标识符,但现在还可以用作对象的属性名。一般来说最好不要用