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

Google Sheets自定义比较函数返回错误值(仅当低值在3-9时)

问题:Google Sheets自定义排球胜负统计函数GETNUMWINS异常

我为Google Sheets编写了自定义函数GETNUMWINS,用于计算排球比赛的胜场数:传入两队的得分范围,若当前队单场得分高于对手则胜场数加1。但存在异常:当败方得分在3到9(含)之间时,函数会误判败方得分更高。

示例数据

Team ATeam B
259
2515

按逻辑Team A应获得2场胜利,但函数返回两队各1胜。

原函数代码

function GETNUMWINS(currentRange, otherRange) {
  var wins = 0;
  var numGames = currentRange.length;

  for(let i = 0; i < numGames; i++){
    if(currentRange[i] > otherRange[i]){
      wins++;
    }
  }
  return wins;
}

问题原因

Google Sheets中,自定义函数接收的范围参数是二维数组(即使是单列范围,每个单元格的值也会被包裹在子数组中)。原代码直接用currentRange[i]和otherRange[i]取到的是子数组(如[25]、[9]),而非实际数值。

当数组与数组比较时,JavaScript会将其转换为字符串后按首字符ASCII码对比:比如[25].toString()是"25",[9].toString()是"9","2"的ASCII码小于"9",因此判定"25" < "9",导致第一场比赛误判为Team B胜。

修复方案

取出二维数组中的实际数值进行比较,修改后的代码如下:

function GETNUMWINS(currentRange, otherRange) {
  var wins = 0;
  var numGames = currentRange.length;

  for(let i = 0; i < numGames; i++){
    const currentScore = currentRange[i][0];
    const otherScore = otherRange[i][0];
    if(currentScore > otherScore){
      wins++;
    }
  }
  return wins;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:53:19