Google Sheets自定义比较函数返回错误值(仅当低值在3-9时)
问题:Google Sheets自定义排球胜负统计函数GETNUMWINS异常
我为Google Sheets编写了自定义函数GETNUMWINS,用于计算排球比赛的胜场数:传入两队的得分范围,若当前队单场得分高于对手则胜场数加1。但存在异常:当败方得分在3到9(含)之间时,函数会误判败方得分更高。
示例数据
| Team A | Team B |
|---|---|
| 25 | 9 |
| 25 | 15 |
按逻辑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
相关产品推荐
相关产品推荐

