You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js结合MySQL2使用reduce分页拆分数组时首元素丢失问题

问题原因

Array.reduce()方法未传入初始累加值是问题的核心诱因:

  • 当reduce没有显式声明第二个参数作为初始值时,首次执行回调函数时累加器会直接取数组的第一个元素(也就是你场景中pid为8的对象),且数组遍历会从索引为1的第二个元素开始执行,因此首条数据不会被推入分组,反而作为结果的根载体存在,后续分组都会挂载在该对象上,完全符合你描述的输出现象。
修复方案

给reduce追加第二个参数[]作为初始累加值即可,修改后的代码如下:

var page_version = 2;
let data = await con.promise().query(`SELECT * FROM News ORDER BY pid DESC`);
var news = data[0];

var result = news.reduce((resultArray, item, index) => {
  const chunkIndex = Math.floor(index/page_version)

  if (!resultArray[chunkIndex]) {
    resultArray[chunkIndex] = []
  }

  resultArray[chunkIndex].push(item)
  return resultArray;
}, []); // 新增空数组作为reduce初始值

console.log(result);

修改后8条测试数据会被正确分为4个长度为2的分组,首条pid为8的数据会被正常放入索引为0的分组中。


内容的提问来源于stack exchange,提问作者sudis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:36:02