条件与循环语句
if 与 switch 如何做分支?
if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else {
statement3;
}
switch (i) {
case 25:
/* falls through */
case 35:
console.log("25 or 35");
break;
default:
console.log("Other");
}
- falls through:
switch命中某个case后会继续执行后续case, 用break控制跳出; - 比较口径:
switch使用严格相等匹配case值;
while 与 for 如何表达循环?
while (condition) {
statement;
}
do {
statement;
} while (expression);
for (initialization; expression; incrementExpression) {
statement;
}
- do-while: 先执行一次再判断, 至少执行一次;
- for: 三个部分都可省略, 与等价
while写法可互相转换;
for-in 与 for-of 遍历什么?
for (const property in object) {
statement;
}
for (const value of iterable) {
statement;
}
- for-in: 遍历对象及其原型链上所有可枚举属性名, 适合读取键;
- for-of: 遍历可迭代对象的值, 依赖
Symbol.iterator, 适合数组、字符串、Map、Set, 详见 迭代器; - 选型: 读键用
for...in, 读值用for...of, 数组避免用for...in;