2015-08-26 43 views
3

我正在Google腳本中編寫我的第一個自定義函數。所有的調試工作都很好,我的代碼完全運行(顯然)。Google Sheet腳本顯然沒有返回數字

有一個已經寫好的函數(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]

但是,當我從具有完全相同的值的電子表格打電話,但在細胞中,表給我一個錯誤:「錯誤:結果不是一個數字」

回答

0

Javascript和谷歌APP-腳本不提供將'返回類型'強制爲自定義函數編號的方法。

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了類似的問題。

相關問題