# 语句

# 1、条件语句

switch 语句和 if else if 语句的区别

  1. 一般情况下,两个语句可以相互替换;
  2. switch…case 语句通常处理 case 为比较确定的值的情况;而 if…else…语句更加灵活,常用于范围判断(大于、等于某个范围);
  3. switch 语句进行条件判断后直接执行到程序的条件语句,效率更高;而 if…else…语句有几种条件,就得判断多少次。
  4. 当分支比较少时,if…else 语句的执行效率比 switch 语句高。
  5. 当分支比较多时,switch 语句的执行效率比较高,而且结构更清晰。

# 2、循环语句

for...in 和 for...of 的区别:

  • for...in 和 for...of 都可以遍历属性
  • fof...in 循环:只能获得对象的键名,不能获得键值
  • for...of 循环:允许遍历获得键值 (es6 的新方法),无法直接遍历对象
const arr = ['one', 'two', 'three'];
for (let arrInKey in arr) {
  console.log(arrInKey);
}
// 0
// 1
// 2

// for...of会输出数组每一个值
for (let arrOfKey of arr) {
  console.log(arrOfKey);
}
// one
// two
// three

// for in 和for of 可以使用 break continue 关键字
for (let arrOfKey of arr) {
  console.log(arrOfKey);
  if (arrOfKey === 'two') {
    break;
  }
}

// for of 遍历对象,可以使用 Object.keys 方法去获取所有属性遍历
const a = { b: 1, c: 2 };
for (var objKey of Object.keys(a)) {
  console.log(objKey);
}

// 不能遍历到symbol属性
const a = Symbol();
const obj = {
  [a]: 'aa',
  name: 'king',
  age: 30,
};
for (let objInkey in obj) {
  console.log(objInkey);
}
// 使用Object.getOwnPropertySymbols()可以遍历symbol属性
const symbolKeys = Object.getOwnPropertySymbols(obj);
// for in 获取的是索引
for (let key2 in symbolKeys) {
  console.log(key2);
}
// for of可以获取到值
for (let key2 of symbolKeys) {
  console.log(key2);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

# 3、class

与函数不同,类声明不会被提升。因此在代码中,不能在还没有声明类之前就使用类。

上次更新: 2/21/2023, 9:39:49 PM