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

如何快速精准计算对象中嵌套数组的长度总和

嘿,这个问题问得很到位!你想要快速累加嵌套数组的长度总和,确实for-in循环在数组遍历场景下不是最优解——它本来是为遍历对象属性设计的,还会踩原型链遍历的坑,这里有几个更快、更精准的方案,绝对能满足你的需求:

推荐方案1:使用Array.reduce()(最简洁高效)

reduce是专门为累加类操作设计的数组原生方法,引擎做了深度优化,代码简洁且结果精准,还能避免空数组的异常情况。

const obj = { name: "abc", arr: [{ key1: "value1", arr1: [1, 2, 3] }, { key1: "value2", arr1: [4, 5, 6] }] };

const totalLength = obj.arr.reduce((sum, currentItem) => {
  return sum + currentItem.arr1.length;
}, 0); // 初始值设为0,确保空数组时返回0而非undefined

console.log(totalLength); // 输出:6

方案2:使用Array.forEach()(直观易懂)

如果你觉得reduce的写法有点绕,forEach是更直白的选择——它也是数组原生遍历方法,不会像for-in那样遍历原型链属性,性能和reduce不相上下。

const obj = { name: "abc", arr: [{ key1: "value1", arr1: [1, 2, 3] }, { key1: "value2", arr1: [4, 5, 6] }] };

let totalLength = 0;
obj.arr.forEach(item => {
  totalLength += item.arr1.length;
});

console.log(totalLength); // 输出:6

方案3:普通for循环(极致性能场景可选)

如果你的数组规模极大(比如十万级以上),普通for循环可以避免函数调用的开销,性能会略胜一筹。不过日常开发中前两个方案已经足够,可读性反而更好。

const obj = { name: "abc", arr: [{ key1: "value1", arr1: [1, 2, 3] }, { key1: "value2", arr1: [4, 5, 6] }] };

let totalLength = 0;
const arrList = obj.arr;
for (let i = 0; i < arrList.length; i++) {
  totalLength += arrList[i].arr1.length;
}

console.log(totalLength); // 输出:6

为什么不推荐for-in?

你提到的for-in循环存在两个关键问题:

  1. 会遍历原型链属性:如果数组的原型上被添加了自定义可枚举属性(比如Array.prototype.myProp = 'test'),for-in会把这些属性也遍历到,导致计算结果错误。
  2. 遍历顺序不固定:for-in的遍历顺序由JavaScript引擎决定,对于数组来说不能保证按索引顺序遍历,可能引发不可预期的问题。

所以用数组原生的遍历方法(reduce/forEach/for循环),不仅速度更快,结果也更精准可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 21:38:13