如何计算对象数组中所有species子数组的总长度?
解决方案
嘿,这个需求挺常见的,我给你几个实用的实现方式,都能轻松得到你想要的总长度4:
方法1:使用reduce(推荐,简洁高效)
reduce是处理这种累加需求的绝佳工具,它会遍历数组里的每一项,把每一项的species数组长度累加到初始值0上,最后返回总和:
let fish = [ { "name": "salmon", "species": [ { "name": "atlantic salmon", "gender": "male" }, { "name": "sockeye salmon", "gender": "female" } ] }, { "name": "carp", "species": [ { "name": "grass carp", "gender": "male" }, { "name": "common carp", "gender": "female" } ] } ]; const totalSpecies = fish.reduce((count, item) => count + item.species.length, 0); console.log(totalSpecies); // 输出:4
方法2:使用forEach循环(直观易懂)
如果你更喜欢直观的循环写法,用forEach也很简单——先初始化一个累加变量,然后遍历每个鱼的对象,把对应species的长度加进去:
let total = 0; fish.forEach(item => { total += item.species.length; }); console.log(total); // 输出:4
方法3:使用flatMap扁平化数组(直观简洁)
flatMap可以先把所有嵌套的species数组合并成一个一维数组,然后直接取这个大数组的长度,结果就是总个数:
const allSpecies = fish.flatMap(item => item.species); console.log(allSpecies.length); // 输出:4
内容的提问来源于stack exchange,提问作者Xon
相关产品推荐
相关产品推荐

