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

JavaScript函数传入两组不同输入仅运行一次该如何解决?

问题原因
  • checkWinner函数逻辑分支覆盖不全,仅在某队平均分是另一队2倍及以上时才会执行打印,其余场景没有任何输出逻辑,第二次调用时两组参数恰好不满足你写的两个胜负判断条件,因此没有打印内容。
  • 你实现的calcAverage平均值计算逻辑错误,平均值应为总分除以参赛场次(这里是3),你写为了总分乘以3,得到的数值完全不符合实际平均分,也是导致判断结果不符合预期的原因。
修复方案
  1. 修正平均值计算逻辑,将calcAverage内的乘法改为除法
  2. 给checkWinner补充不满足获胜条件时的兜底输出分支
修复后完整代码
const data1dolphins = 44 + 23 + 71;
const data1Koalas = 65 + 54 + 49;
const data2dolphins = 85 + 54 + 41;
const data2Koalas = 23 + 34 + 27;

function calcAverage(totalScore, matchCount) {
  // 平均值=总分/参赛场数,修正为除法
  const scoreAverage = totalScore / matchCount
  return scoreAverage;
}

const data1DolphinsAverage = calcAverage(data1dolphins, 3)
const data1KoalasAverage = calcAverage(data1Koalas, 3)
const data2DolphinsAverage = calcAverage(data2dolphins, 3)
const data2KoalasAverage = calcAverage(data2Koalas, 3)

function checkWinner(avgTeamOne, avgTeamTwo) {
  if (avgTeamOne >= (avgTeamTwo * 2)) {
    console.log(`team one won with average score of : ${avgTeamOne}, while team two lost with average score of : ${avgTeamTwo}`)
  } else if (avgTeamTwo >= (avgTeamOne * 2)) {
    console.log(`team two won with average score of : ${avgTeamTwo}, while team one lost with average score of : ${avgTeamOne}`)
  } else {
    // 补充兜底分支,没有队伍满足获胜条件时打印
    console.log(`No team wins, team one average: ${avgTeamOne}, team two average: ${avgTeamTwo}`)
  }
}

console.log('before')
checkWinner(data1DolphinsAverage, data1KoalasAverage)
console.log('middle')
checkWinner(data2DolphinsAverage, data2KoalasAverage)
console.log('after')
修复后运行输出

before
No team wins, team one average: 46, team two average: 56
middle
team one won with average score of : 60, while team two lost with average score of : 28
after

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:54:04