3. 数组常用方法
1. reduce 返回值
// Array.prototype.reduce() 方法
// 作用:对数组中的每个元素执行一个 reducer 函数,将其结果汇总为单个返回值
// 基本语法:
const result = array.reduce(callback(accumulator, currentValue, index, array) {
// 返回新的累加器值
}, initialValue)
// 参数:
// callback: 执行每个元素的函数
// - accumulator: 累加器,存储回调的返回值
// - currentValue: 当前元素
// - index (可选): 当前索引
// - array (可选): 原始数组
// initialValue (可选): accumulator 的初始值

问题一: total为什么不是+=
// 1. total 为什么不是 += ?
// 因为 reduce 的回调函数需要返回新的 total 值
// 不是修改原有的 total,而是每轮返回新值
const withInit = [1, 2, 3].reduce((sum, n) => sum + n, 0)
// 第一次:sum=0, n=1 → 1
// 第二次:sum=1, n=2 → 3 // sum就是上一轮返回的值
// 第三次:sum=3, n=3 → 6
问题二: ,0)是什么?
// 这是 reduce 的第二个参数:初始值
array.reduce(callback, initialValue)
// ↑
// 初始值
// 没有初始值 vs 有初始值:
// 有初始值:
const withInit = [1, 2, 3].reduce((sum, n) => sum + n, 0)
// 第一次:sum=0, n=1 → 1
// 第二次:sum=1, n=2 → 3
// 第三次:sum=3, n=3 → 6
// 没有初始值(第一个元素作为初始值):
const withoutInit = [1, 2, 3].reduce((sum, n) => sum + n)
// 第一次:sum=1, n=2 → 3
// 第二次:sum=3, n=3 → 6
// 结果相同,但数组为空时会出错
2.map 返回数组
// 1. 数组的 .map 方法
// 语法:array.map(callback(element, index, array))
// 作用:遍历数组,对每个元素执行回调函数,返回新数组
// 示例:
const numbers = [1, 2, 3]
const doubled = numbers.map(num => num * 2) // [2, 4, 6]
// 2. 你的代码解释
const periods: [string, string][] = [["08:00", "12:00"], ["13:00", "15:00"]]
// 方案A: 使用 map + join
const result1 = periods.map(([start, end]) => `${start}-${end}`).join("#")
console.log(result1)
// 执行过程:[["08:00", "12:00"], ["13:00", "15:00"]]
// 1. map: ["08:00-12:00", "13:00-15:00"]
// 2. join: "08:00-12:00#13:00-15:00"
// 执行结果: "08:00-12:00#13:00-15:00"
// 方案B: 使用 reduce
const result2 = periods.reduce((str, [start, end]) => str + start + "-" + end + "#", "")
console.log(result2)
// 执行过程:
// 1. 初始: ""
// 2. 第一次: "" + "08:00-12:00#" = "08:00-12:00#"
// 3. 第二次: "08:00-12:00#" + "13:00-15:00#" = "08:00-12:00#13:00-15:00#"
// 执行结果: "08:00-12:00#13:00-15:00#"
- Title: 3. 数组常用方法
- Author: 明廷盛
- Created at : 2026-02-12 01:17:04
- Updated at : 2026-02-02 13:32:00
- Link: https://blog.20040424.xyz/2026/02/12/🐍爬虫工程师/第二部分 JS逆向/0.JS学习/3. 数组常用方法/
- License: All Rights Reserved © 明廷盛