操作流程
条件
if 语句
if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else {
statement3;
}
switch 语句
switch (i) {
case 25:
/* falls through */
case 35:
console.log("25 or 35");
break;
default:
console.log("Other");
}
falls through
- switch 语句命中 case 后, 继续执行下一个 case;
- 通过 break 控制;
循环
while 语句
while (condition) {
statement;
}
do-while 语句
do {
statement;
} while (expression);
for 语句
- 三部分可选;
for (initialization; expression; incrementExpression) {
statement;
}
等效的 while 语句
initialization;
while (expression) {
console.log(i);
statement;
incrementExpression;
}
for-in 语句
- 遍历对象原型链所有可枚举属性;
for (property in expression) {
statement;
}
for-of 语句
- 遍历对象原型链所有可迭代属性;
for (property of expression) {
statement;
}
for...in 和 for...of 的区别
- for in 一般用来遍历对象的 key;
- for of 一般用来遍历数组的 value;
跳转
Labeled 语句
- 标识 statement, 用于 continue 和 break;
start: for (let i = 0; i < count; i++) {
console.log(i);
}
break 和 continue 语句
break
- 跳出最近的 loop 或 switch;
- 跳出指定 labeled statement;
let num = 0;
outermost: for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
if (i == 5 && j == 5) {
break outermost;
}
num++;
}
}
console.log(num); // 55
continue
- break 的跳过版本;
let num = 0;
outermost: for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
if (i == 5 && j == 5) {
continue outermost;
}
num++;
}
}
console.log(num); // 95
with 语句
- 简化多次调用同一对象的操作;
- 并将 with 对象对应的 execution context 移动至 scope chain 最前端;
- strict mode 禁止使用;
let qs = location.search.substring(1);
let hostName = location.hostname;
let url = location.href;
with (location) {
let qs = search.substring(1);
let hostName = hostname;
let url = href;
}