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

JavaScript按zs_numero分组取zs_score最大值并计算加权总和实现问题

问题排查

你的代码存在以下2个核心错误,另有1个潜在隐患:

  • 累加计算的for循环中没有通过下标访问数组元素:newarray是数组对象,直接取newarray.zs_coefficient会得到undefined,和数字运算后结果为NaN,必须通过newarray[i]访问对应下标的元素
  • 累加变量没有初始化:你没有给累加变量设置初始值0,未定义的变量参与运算也会得到NaN
  • 潜在隐患:原数组中的zs_coefficient、zs_score都是字符串类型,虽然JS会做隐式转换,但显式转换为数字可以避免边界场景下的逻辑错误

正确实现代码

var newarray = []
result.entities.forEach(function (a) {
    // 显式转换为数字,避免字符串运算问题
    const currentScore = Number(a.zs_score);
    const currentCoeff = Number(a.zs_coefficient);
    if (!this[a.zs_numero]) {
        this[a.zs_numero] = { 
            zs_numero: a.zs_numero, 
            zs_coefficient: currentCoeff, 
            zs_score: currentScore 
        };
        newarray.push(this[a.zs_numero]);
        return;
    }
    // 仅当当前分数更高时更新
    if (currentScore > this[a.zs_numero].zs_score) {
        this[a.zs_numero].zs_score = currentScore;
    }
}, Object.create(null));

// 初始化累加变量,通过下标访问数组元素
var total = 0;
for(var i = 0; i < newarray.length; i++){
  total += newarray[i].zs_coefficient * newarray[i].zs_score;
}

console.log(newarray);
console.log('累加总和:', total);

按示例数据计算最终累加结果为2*55 + 4*10 + 3*35 = 255。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:54:08