3

我对谷歌应用程序脚本相当陌生,在尝试“你的第一个自定义函数”教程时遇到了这个问题。

=in2mm(1) -> 25.4
=in2mm(2) -> 50.8
=in2mm() -> #ERROR (error: input must be a number (line 6))
=in2mm(pi()) -> 79.7964534011807
=in2mm(a) -> #NAME? (error: Unknown range name a)
=in2mm(*) -> #ERROR (error: Parse error)

我试图了解谷歌应用程序脚本中“投掷”功能的用法。它如何能够在我的第 3 行中产生“输入必须是数字”,而第 5 行和第 6 行会产生其他一些结果?

4

2 回答 2

2

您可以通过添加一些这样的案例处理来使错误消息更加明确:

function in2mm(inNum) {
  // Function to convert from INCHES to MILLIMETERS
  var outNum = 0;     // this will hold the answer
  var factor = 25.4;  // multiply input by this factor to get output
    if (inNum == "") {  // check to make sure input is a number
    throw ("error: input must not be empty");  // throw an exception with the error message
    }else if (typeof inNum != "number") {  // check to make sure input is a number
    throw ("error: input must be a number (now it is a "+typeof inNum+")");  // throw an exception with the error message
}
  outNum = inNum * factor;  // calculate the answer
  return outNum;  // return the answer to the cell which has the formula
}

但是该参数必须是“有效”才能由函数处理...在您的示例中,=in2mm(a)a 被解释为命名区域,并且由于您没有名为“a”的区域,因此在尝试执行之前会出错功能。这就是为什么错误消息不是来自函数本身而是来自电子表格下的“引擎”的原因。

另一个示例=in2mm(*)出于同样的原因返回 Parse 错误,参数无效,在这种情况下它也不能是一个范围......你也可以尝试 + 或 - ,它会尝试计算一些东西,但它不能并且错误消息再次来自电子表格,而不是来自您的函数。

尝试使用有效范围并更改目标单元格中​​的值,您将看到完全不同的结果。例如在A2=in2mm(A1) 和玩A1

希望我让事情变得(一点)更清楚;-)

于 2012-08-05T16:17:48.370 回答
0

如果您在代码中发现错误,那么您可以抛出您在提供的第三个示例中看到的错误。例如,代码看起来像......

function in2mm(inches){
  if (inches == null){ 
    throw 'input must be a number'; 
  }
}

在您提供的最后两个示例中,错误没有被您的函数捕获,而是被 Google 电子表格捕获。

于 2012-08-05T16:01:25.150 回答