RangeError: 无效数组长度
错误信息
无效数组长度
快速摘要
你 tried 到创建 or resize 数组使用无效长度 — 负, 非-integer, or 也大.
为什么发生
通过负 数字到 数组 constructor
通过非-integer (float) as 数组长度
设置数组.长度到 无效值
最小示例
✗ 错误代码
const arr = new Array(-1);✓ 修复代码
const size = Math.max(0, Math.floor(-1));
const arr = new Array(size);负数组长度是 无效. Sanitize 使用 Math.最大值(0, ...) 到 ensure 有效长度.
如何诊断
检查值 是通过到 新数组() or assigned 到 .长度
Ensure 值是 非-负 integer
Log 值到 see 如果它 是负 or float
如何修复
Use Math.最大值(0, Math.floor(值)) 到 sanitize 长度
验证输入是 非-负 integer 之前 using 它
Use 数组 literals [...] 相反的 新数组(n) 当可能
如何预防
验证 numeric 输入之前 using 它们 as 数组长度
Prefer 数组 literals over 数组 constructor