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

new Array()构造数组致expect().toEqual()测试失败问题咨询

为什么用new Array()初始化数组会导致Jest的expect().toEqual()断言失败?

我来帮你拆解这个问题——其实核心和JavaScript的稀疏数组以及Jest的比较逻辑有关,咱们一步步说:

问题重现

先看你的代码:

分块函数(index.js)

function chunk(array, size) {
  const chunked = new Array(); // 改为[]测试通过
  for (let i = 0, j = 0; i < array.length; i += size, j++) {
    chunked[j] = array.slice(i, i + size); // 改用push()也能通过
  }
  return chunked;
}

Jest测试代码

const chunk = require('./index');
describe('Chunk function', () => {
  test('should correctly divide an array of 10 elements with chunk size 2', () => {
    const chunked = chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2);
    expect(chunked).toEqual([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]);
  });
});

错误原因分析

你碰到的问题本质上和**稀疏数组(Sparse Arrays)**以及Jest的版本/比较逻辑有关:

  1. new Array() + 索引赋值的潜在问题
    当你用new Array()创建空数组后,直接通过索引(比如chunked[j])赋值时,如果当前索引j大于等于数组的length,JavaScript会自动把数组的length扩展到j+1,但中间未赋值的位置会被填充成empty slots(空洞)——这些位置在数组中“存在”但没有实际值,用0 in chunked检查会返回false。
    虽然你的代码里j是从0开始连续递增的,理论上不会产生空洞,但旧版本的Jest在比较new Array()创建的数组和字面量数组时,可能会因为数组的内部表示(比如创建方式、隐藏属性)不同而误判,导致断言失败。

  2. 为什么改用[]或push()就能通过?

    • 数组字面量[]创建的数组,在连续索引赋值时,和new Array()的结果逻辑上一致,但现代Jest对字面量数组的处理更直观,不会触发旧版本的兼容性问题;
    • push()方法是JavaScript数组添加元素的标准方式,它会自动扩展数组并在末尾添加元素,完全不会产生空洞,而且不需要维护额外的j变量,代码更简洁可靠。

解决方案

推荐两种方式,第二种更简洁安全:

方式1:改用数组字面量初始化

function chunk(array, size) {
  const chunked = []; // 替换new Array()为字面量
  for (let i = 0, j = 0; i < array.length; i += size, j++) {
    chunked[j] = array.slice(i, i + size);
  }
  return chunked;
}

方式2:使用push()方法(更推荐)

去掉多余的j变量,直接用push()添加分块结果:

function chunk(array, size) {
  const chunked = [];
  for (let i = 0; i < array.length; i += size) {
    chunked.push(array.slice(i, i + size));
  }
  return chunked;
}

内容的提问来源于stack exchange,提问作者user-9725874

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:09:21