跳到主要内容

条件与循环语句

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;