2012-08-05 57 views
2

我对Google应用程序脚本相当陌生,在尝试使用“您的第一个自定义函数”教程时遇到此问题。Google Apps教程:您的第一个自定义函数

=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) 

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

回答

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'的区域,它会在尝试执行该函数之前发生错误。这就是为什么错误信息不是来自函数本身,而是来自电子表格下的'引擎'。

另一个例子=in2mm(*)返回一个解析错误出于同样的原因,该参数无效,在这种情况下,它不能是一个范围要么...你也可以尝试+或 - ,它会试图计算的东西,但它不能再一次从电子表格中获取错误消息,而不是从您的函数中获取。

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

希望我做的东西(小)更清楚一点;-)

+0

感谢抓到澄清的有效范围,可以播放由电子表格下的'引擎'使用。在添加了附加的代码不改变我的3行至: = in2mm() - >“错误:错误:输入必须是一个数字(现在它是一个未定义)(第8行)” 的其余部分保持不变。 现在我也明白,a被解释为名称区域,符号由于电子表格而不是我的函数而无效。 – 2012-08-06 01:40:26

0

如果您在代码中发现错误,那么您可以抛出错误,这是您在第三个示例中看到的错误。作为一个例子,代码看起来像......

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

在你提供的最后两个例子中,错误不是由你的函数抓住了,但由谷歌电子表格是相当抓获。

+0

感谢澄清的错误是由谷歌电子表格 – 2012-08-06 00:29:53