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

JavaScript:统计指定水果列表在多维数组中的权重总和

问题:统计水果对应子数组的count总和

需求说明

给定水果列表:

var list = [apple, watermelon, pineapple]

以及包含水果子数组和对应权重的对象:

var array = { 
  fruit : [ [apple], [apple, watermelon], [pineapple, watermelon], [watermelon], [pineapple], [apple, pineapple] ],
  count : [4, 7, 5, 3, 3, 2]
}

需要生成一个新对象,统计每个水果对应的所有包含它的子数组的count值之和,预期结果:

result = {
  fruits : [apple, watermelon, pineapple],
  count : [13, 15, 10]
}

你的错误代码

var result = {
    trigger : [apple, watermelon, pineapple],
    count : []
}
for (i=0; i < array.fruits.length; i++){
    var k = 0
    for (j in result.trigger){
        if (array.fruits[i].includes(j)) {
            k += array.count[i]
        }
        result.count.push(k)
    }
}

错误分析

  1. 变量名拼写错误:原对象的水果数组是array.fruit,你写成了array.fruits,导致循环条件i < array.fruits.length不成立(array.fruits为undefined,length为NaN),外层循环根本没执行,count数组自然全是0。
  2. for...in遍历数组的误区:for (j in result.trigger)中的j是数组的索引(字符串类型,比如"0"、"1"),不是水果元素,所以array.fruits[i].includes(j)永远为false,无法触发累加逻辑。
  3. count数组更新逻辑错误:每次内层循环都执行result.count.push(k),会导致count数组长度远超预期;且你没有针对每个水果单独维护累加值,而是用一个k全局覆盖,逻辑完全错误。

修正后的代码

// 初始化结果对象,count数组先填充0,对应每个水果的初始总和
var result = {
    fruits: [apple, watermelon, pineapple],
    count: [0, 0, 0]
};

// 遍历每个子数组及其对应的count值
for (let i = 0; i < array.fruit.length; i++) {
    const currentFruits = array.fruit[i];
    const currentCount = array.count[i];
    
    // 遍历结果中的每个水果,判断是否在当前子数组中
    for (let j = 0; j < result.fruits.length; j++) {
        if (currentFruits.includes(result.fruits[j])) {
            // 若存在,累加对应count值
            result.count[j] += currentCount;
        }
    }
}

console.log(result);
// 输出:{ fruits: [apple, watermelon, pineapple], count: [13, 15, 10] }

代码逻辑说明

  1. 先初始化结果对象的count数组为全0,每个位置对应fruits数组中对应索引的水果总和。
  2. 外层循环遍历array.fruit中的每个子数组,同时获取对应的count值。
  3. 内层循环遍历结果中的每个水果,检查当前子数组是否包含该水果,若包含则将当前count值累加到对应位置的总和中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 07:27:03