gpt4 book ai didi

javascript - Google Sheet 脚本显然没有返回数字

转载 作者:行者123 更新时间:2023-12-02 19:29:46 25 4
gpt4 key购买 nike

我正在用 Google 脚本编写我的第一个自定义函数。一切都在调试中运行良好,我的代码运行(显然)完美。

已经编写了一个函数(CONVERT_RACETIME_TO_SECONDS),它接受特定格式的字符串,然后返回秒数。

然后,该函数应采用两个范围,并将第二个范围的最高值除以第一个范围的最低值。

  /**
* A function that takes two ranges of values and returns a single value.
* Returns the percentage of the maximum of the second range over the minimum of the first range.
* this is equal to max(secondrange)/min(firstrange)
*
* @param {Array} fast The Range of fastest times
* @param {Array} slow The Range of slowest times
* @return The calculated ratio.
* @customfunction
*/
function SLOWEST_RATIO(fast, slow) {
if (!(fast instanceof Array) || !(slow instanceof Array) ) {
throw 'Invalid: range input required';
}

var fastest = Math.min.apply(null, fast.map(CONVERT_RACETIME_TO_SECONDS));
var slowest = Math.max.apply(null, slow.map(CONVERT_RACETIME_TO_SECONDS));
var ratio = slowest/fastest;

var ratiotype = typeof ratio;

if (!(ratiotype == 'number')) {
throw 'Invalid: ratiotype is ' + ratiotype;
}

return ratio;
}

function test_slowest_ratio() {
var fastest = ['21:03.55','21:43.83','22:41.31','23:32.44'];
var slowest = ['31:11.29','31:19.18','33:05.22','28:17.76'];

var ratio = SLOWEST_RATIO(fastest, slowest);

Logger.log('Ratio should be a non-zero number: ' + ratio + ' (is ' + (typeof ratio) + ')');
}

它使用第二个函数进行了完美的测试。

[15-08-26 17:42:04:396 BST] Starting execution [15-08-26 17:42:04:403 BST] Logger.log([Ratio should be a non-zero number: 1.5711447904712912 (is number), []]) [0 seconds] [15-08-26 17:42:04:404 BST] Execution succeeded [0.002 seconds total runtime]

但是当我从具有完全相同值但在单元格中的电子表格调用时,表格会给出一个错误:“错误:结果不是数字”

最佳答案

Javascript 和 Google 应用脚本不提供“强制”自定义函数的返回类型为数字的方法。

This答案很接近,但返回类型是数组,而不是数字。

这个问题的答案question是正确的,但没有关于如何强制返回值的正确类型的示例。

这个link有将 Javascript 字符串转换为数字的示例,并列出了一些陷阱。

为了“强制”返回数字,请将 return Number(ratio); 添加到函数中:

  function SLOWEST_RATIO(fast, slow) {
if (!(fast instanceof Array) || !(slow instanceof Array) ) {
throw 'Invalid: range input required';
}

var fastest = Math.min.apply(null, fast.map(CONVERT_RACETIME_TO_SECONDS));
var slowest = Math.max.apply(null, slow.map(CONVERT_RACETIME_TO_SECONDS));
var ratio = slowest/fastest;

var ratiotype = typeof ratio;

if (!(ratiotype == 'number')) {
throw 'Invalid: ratiotype is ' + ratiotype;
}

return Number(ratio);
}

查看我的question & answer对于类似的问题。

关于javascript - Google Sheet 脚本显然没有返回数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32232191/

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