流程控制决定代码走向,函数把逻辑打包复用。本篇讲两大基石的写法与陷阱,结尾附评级函数小案例。
一、条件判断
// if / else if / else
if (score >= 90) {
console.log('优秀');
} else if (score >= 60) {
console.log('及格');
} else {
console.log('不及格');
}
// switch(注意 break 穿透!)
switch (type) {
case 'a':
case 'b': // 共享分支
handleAB();
break;
case 'c':
handleC();
break; // 漏 break 会继续执行下一分支
default:
handleOther();
}
// 短路写法
const name = input || '默认'; // falsy 取默认
const n2 = input ?? '默认'; // 仅 null/undefined 取默认(更准)
isLogin && showWelcome(); // 条件执行
二、循环
// 经典 for(控制索引)
for (let i = 0; i < arr.length; i++) { ... }
// while / do-while
while (queue.length) { process(queue.shift()); }
// for...of(遍历可迭代对象的值,推荐)
for (const item of [1, 2, 3]) { console.log(item); }
// for...in(遍历对象的键,不要用于数组!)
for (const key in { a: 1, b: 2 }) { console.log(key, obj[key]); }
// 数组专用
arr.forEach((v, i) => console.log(i, v));
| 场景 | 用法 |
|---|---|
| 索引控制 | for |
| 数组/字符串遍历 | for...of / forEach |
| 对象键遍历 | for...in |
| 条件循环 | while / do-while |
| 需要 break/continue | for / for...of(forEach 不能中断) |
三、函数声明
// 函数声明(会提升,可先调用后声明)
function add(a, b) { return a + b; }
// 函数表达式
const add = function(a, b) { return a + b; };
// 箭头函数(简洁、无自己的 this)
const add = (a, b) => a + b; // 单表达式自动 return
const fn = x => ({ val: x }); // 返回对象要加括号
// 默认参数与剩余参数
function greet(name = '游客', ...others) {
return `你好 ${name} ${others.join(' ')}`;
}
greet('Tom', 'a', 'b'); // "你好 Tom a b"
四、箭头函数 vs 普通函数
| 对比 | 普通函数 | 箭头函数 |
|---|---|---|
| this | 调用时决定 | 定义时继承外层 |
| arguments | 有 | 无(用 ...args) |
| 可 new | ✅ | ❌ |
| 适用 | 方法/构造器 | 回调(map/filter/事件) |
五、注意
- switch 用 === 比较,漏 break 会穿透;
- for...in 遍历数组会带上原型链属性,数组用 for...of;
- 箭头函数不要当对象方法(this 会指错,见 this 篇);
- 函数命名用动词(get/set/handle/is 开头表布尔)。
六、小案例:成绩评级函数
// 评级 + 批量处理
function grade(score) {
if (typeof score !== 'number' || Number.isNaN(score)) return '无效';
if (score < 0 || score > 100) return '越界';
switch (true) { // switch(true) + 条件表达式
case score >= 90: return '优秀';
case score >= 80: return '良好';
case score >= 60: return '及格';
default: return '不及格';
}
}
// 批量评级(filter + map)
const scores = [95, 72, 58, 88, 101, NaN];
const pass = scores.filter(s => grade(s) !== '不及格' && grade(s) !== '无效' && grade(s) !== '越界');
const report = scores.map(s => `${s} → ${grade(s)}`);
console.log(report);
// ['95 → 优秀', '72 → 及格', '58 → 不及格', '88 → 良好', '101 → 越界', 'NaN → 无效']
函数封装校验 + switch(true) 区间 + map/filter 批处理 —— 流程控制与函数的综合演练。
七、总结
if 管区间、switch 管多值(防穿透);for...of 遍历值、for...in 遍历键;箭头函数简写但 this 继承外层;默认参数/剩余参数常用;函数先想输入输出再实现。