gpt4 book ai didi

javascript - 忽略 Google 表格自定义脚本中的空单元格

转载 作者:行者123 更新时间:2023-12-02 21:58:39 24 4
gpt4 key购买 nike

我正在尝试创建一个公式来计算 Google 表格上的净推荐值。我的公式有效,但只有当我指定确切的范围时。我的问题是,随着时间的推移,这个特定的工作表将随着数据的增长而增长,我不想继续重新选择范围。我想要做的是选择整行并让它自动更新 NPS 分数。我对这种方法的问题是每个空单元格都被认为是零,这搞砸了我的百分比。如何让我的函数忽略空单元格???

这是我的尝试:

/**
This is a custom formula that calculates the Net Promoter Score.
@customFunction
*/
function NPS(numArr) {

var detractors = new Array();
var passive = new Array();
var promoters = new Array();

var i = 0;

for (i = 0; i < numArr.length; i++) {
if (isNaN(numArr[i])) {
console.log(numArr[i]);
} else {
if (numArr[i] >= 9) {
promoters.push(numArr[i]);
} else if (numArr[i] === 7 || numArr[i] === 8) {
passive.push(numArr[i]);
} else if (numArr[i] <= 6) {
detractors.push(numArr[i]);
}
}
}


var promoPercentage = promoters.length / numArr.length;
var detractorsPercentage = detractors.length / numArr.length;

return (promoPercentage - detractorsPercentage) * 100;
}

最佳答案

您可以使用 JavaScript filter [1] 函数从您获取的数组 (numArr) 中过滤空值。另请注意,您选择了一系列单元格,因此参数将是一个二维数组 [2],其中每个值都是一个“行”数组,其中填充了该行的列值,以防您只需要第一个值每行的(对于像 A1:A25 这样的单列范围),您需要访问每个“行”数组的第一个元素才能获取实际值:

function NPS(numArr) {

var detractors = new Array();
var passive = new Array();
var promoters = new Array();

var i = 0;

//Filter empty elements
numArr = numArr.filter(function(element) {
return element[0] !== '';
})

for (i = 0; i < numArr.length; i++) {
if (isNaN(numArr[i][0])) {
console.log(numArr[i][0]);
} else {
if (numArr[i][0] >= 9) {
promoters.push(numArr[i][0]);
} else if (numArr[i][0] === 7 || numArr[i][0] === 8) {
passive.push(numArr[i][0]);
} else if (numArr[i][0] <= 6) {
detractors.push(numArr[i][0]);
}
}
}

var promoPercentage = promoters.length / numArr.length;
var detractorsPercentage = detractors.length / numArr.length;

return (promoPercentage - detractorsPercentage) * 100;
}

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

[2] https://developers.google.com/apps-script/guides/sheets/functions#arguments

关于javascript - 忽略 Google 表格自定义脚本中的空单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59939050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com