用三条温度记录对比 Array.with() 和 slice() 复制时对空槽的处理,解释索引 1 为什么会多触发一次 map() 回调。
用 with() 更新稀疏数组后,map() 为什么多跑了一次?
时间:2026-12-01
浏览:659
文章目录
一张温度表记录了三个时段的读数,中间那个时段没收到采样,数组里留了个空槽。用 with(-1, 19) 修正末尾读数后,对副本调用 map(),原本被跳过的索引 1 也触发了回调。这个变化发生在复制数组时。
同样读到 undefined,属性却不一样
[15, , 18] 的长度是 3。这个数组在索引 1 没有属性,读取 readings[1] 得到 undefined。写成 [15, undefined, 18] 也会读到 undefined,但这次索引 1 有自己的属性。下面用 Object.hasOwn() 看复制前后的差异,再记下 map() 回调实际收到的索引。
const readings = [15, , 18];
const corrected = readings.with(-1, 19);
function visitedSlots(samples) {
const visited = [];
samples.map((_, index) => visited.push(index));
return visited.join(', ');
}
console.log('Before, index 1 exists:', Object.hasOwn(readings, 1));
console.log('After, index 1 exists:', Object.hasOwn(corrected, 1));
console.log('After, index 1 value:', corrected[1]);
console.log('Before, map indices:', visitedSlots(readings));
console.log('After, map indices:', visitedSlots(corrected));

方法 with(-1, 19) 会将负索引 -1 解析为最后一项的索引 2。原数组中索引 2 的值保持为 18 不变,而新创建的副本则在索引 2 处写入值 19。对于索引 0 和 1,with() 会先读取原数组对应位置的值,随后将这些值作为属性写入新数组。
额外的一次回调源自何处
在索引 1,with() 读到 undefined,并把它写成新数组自己的属性。map() 每到一个索引,会先查这个属性是否存在,查找范围包括原型链。本例的原型链上也没有索引 1,所以原数组跳过这个位置,副本则以 undefined 调用一次回调。

把 -1 换成 2,得到的副本一样,索引 1 仍会被填上。换算后的索引一旦越界,with() 会抛出 RangeError。例如长度为 3 时传入 -4。
要跳过缺失采样,先复制再赋值
若业务约定遇到空槽即跳过格式化操作,可先通过 slice() 创建数组副本,再修改副本的最后一项。此方式能保留原有的空槽结构,使得 map() 生成的标签数组仅包含索引 0 和 2 对应的元素。
const readings = [15, , 18];
const corrected = readings.slice();
corrected[corrected.length - 1] = 19;
const labels = corrected.map(value => `${value} °C`);
console.log('Original last value:', readings[2]);
console.log('Corrected last value:', corrected[2]);
console.log('Index 1 exists:', Object.hasOwn(corrected, 1));
console.log('Label indices:', Object.keys(labels).join(', '));

如果温度表要显示每个时段,可以用明确的值记录缺失采样,再由格式化函数决定怎么显示。写回归测试时,可以固定一组带空槽的输入,同时断言更新后的读数和回调收到的索引。只测最后一项是不是 19,会漏掉多跑的那次回调。
实用工具推荐
绿化、压缩、噪点和虚拟水印,自由调节做旧程度。
选择画质和输出格式,预览压缩前后的大小。