Google电子表格脚本使用数组

时间:2016-06-01 15:10:18

标签: javascript google-sheets spreadsheet

我在谷歌脚本中制作了这个功能

function gemOMVG(values) {
  var sum = "";

  for (var i = 0; i < values.length; i++) { 
  sum = sum+values[i];
  }

 return sum;
}

我有一系列三个水平单元格,其值为&#39; o&#39; &#39; V&#39; &#39;克&#39 ;.我的脚本返回o,v,g由komma分隔。我想在数组中包含这些值,以便我可以执行if语句。

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我明白了!

function gemOMVG(values) {
  var sum = 0;

  for (var i = 0; i < values[0].length; i++) { 
  //sum += "-"+values[0][i]; 
    if(values[0][i] == 'o'){sum+= 4.5;} 
    else if (values[0][i] == 'm'){sum+= 5;}
    else if (values[0][i] == 'v'){sum+= 6.2;}
    else if(values[0][i] == 'g'){sum+= 8.5;}
  }

  var gem = sum/values[0].length;

  var array = [4.5, 5, 6.2, 8.5];

 function closest(arr, closestTo){

    var closest = Math.max.apply(null, arr); //Get the highest number in arr in case it match nothing.

    for(var i = 0; i < arr.length; i++){ //Loop the array
        if(arr[i] >= closestTo && arr[i] < closest) closest = arr[i]; //Check if it's higher than your number, but lower than your closest value
    }

    return closest; // return the value
}

var roundgem = closest(array, gem);
  if(roundgem == 4.5){return "o";}
  else if(roundgem == 5){return "m";} 
  else if(roundgem == 6.2){return "v";} 
  else if(roundgem == 8.5){return "g";}
}