【问题标题】:Google Sheet Script apparently not returning a numberGoogle Sheet Script 显然没有返回数字
【发布时间】:2015-08-26 16:43:21
【问题描述】:

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

已经编写了一个函数 (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] 开始执行 [15-08-26 17:42:04:403 BST] Logger.log([Ratio 应该是一个非零数:1.5711447904712912 (is number), []]) [0 seconds] [15-08-26 17:42:04:404 BST] 执行 成功 [0.002 秒总运行时间]

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

【问题讨论】:

    标签: javascript google-apps-script google-sheets


    【解决方案1】:

    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 了解类似问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 2015-06-09
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 2021-09-08
      • 2021-07-19
      相关资源
      最近更新 更多