1.arr.reduce
reduce 是 JavaScript 数组上非常强大的高阶函数,用来把数组“归约”为单个值(数字、对象、数组、字符串,甚至是 Promise)。它把数组每一项与“累积值”(accumulator)按某种规则合并,最终返回一个值。
函数签名
arr.reduce(callback[, initialValue])
callback 的签名:
(accumulator, currentValue, currentIndex, array) => newAccumulator
- accumulator:上一次回调返回的累积结果(第一次迭代为 initialValue,若未提供则为数组的第一个元素)。
- currentValue:当前处理的数组元素。
- currentIndex:当前元素的索引(当没提供 initialValue 时,第一次迭代索引是 1)。
- array:正在被遍历的原数组。
- initialValue(可选):指定第一次调用回调时 accumulator 的初始值。
细节
- 有 initialValue 的情况:迭代从索引 0 开始,accumulator 初始为 initialValue。
-
无 initialValue 的情况:
- accumulator 初始为数组第一个被定义的元素(注意:稀疏数组会跳过“空槽”)。迭代从该元素之后的下一个已定义索引开始。
- 如果数组为空且未提供 initialValue,会抛出 TypeError。
- 稀疏数组(sparse arrays):reduce 会跳过不存在的索引(不会把 undefined 当作存在的元素除非那个位置确实有 undefined 值)。
- 复杂数据类型:accumulator 可以是任意类型(对象、数组、字符串、函数等)。
- 时间复杂度:一般是 O(n)。
示例
求和(有/无 initialValue)
const nums = [1, 2, 3, 4];
// 有 initialValue
const sumA = nums.reduce((acc, cur) => acc + cur, 0); // 10
// 无 initialValue
const sumB = nums.reduce((acc, cur) => acc + cur); // 10
细步演示(无 initialValue)
- 初始:acc = 1(数组第一个元素),迭代从索引1开始
- idx1: acc = 1 + 2 = 3
- idx2: acc = 3 + 3 = 6
- idx3: acc = 6 + 4 = 10
2.JS 中“空”的几种常见表示
| 值 | 类型 | 说明 | 举例/场景 |
|---|---|---|---|
undefined |
undefined |
表示变量已声明但未赋值,或对象属性、函数返回值不存在。 | js let a; console.log(a); // undefined |
null |
object |
表示有意地设置为空值,通常用于对象、DOM、引用类型。 | js let obj = null; |
NaN |
number |
“不是一个数字”(Not-a-Number),通常是计算失败的结果。 | js parseInt("abc"); // NaN |
"" |
string |
空字符串,表示字符串存在但没有字符。 | js let str = ""; |
0 |
number |
数字存在,但数值为 0。某些情况下也被视为空。 | js if (0) console.log("不会执行"); |
false |
boolean |
布尔假值,可表示“空逻辑”。 | js if (false) console.log("不会执行"); |
[] |
object (Array) |
空数组,表示存在列表但内容为空。 | js let arr = []; |
{} |
object |
空对象,表示存在对象但无属性。 | js let obj = {}; |
Top comments (0)