如何使用谷歌应用程序脚本获取数组中的值的索引

时间:2017-06-15 22:54:02

标签: javascript google-apps-script

function convertToEnts(formObject){
  var sheet = SpreadsheetApp.getActiveSheet();
  var columns = sheet.getRange(1,1,1, sheet.getLastColumn()).getValues()[0];
  var columnValues = String(columns).split(",");  //this is something I tried on the advise of https://stackoverflow.com/questions/17044825/indexof-returning-1-despite-object-being-in-the-array-javascript-in-google-sp
  var data = sheet.getRange(2, 1,sheet.getLastRow()-1,sheet.getLastColumn()).getValues();
  for (var i=0;data.length;i++){
    row = data[i];
    var entity = {}
    //formObject: {identity=lat,...,other form attributes here}
    for (var key in formObject){
      Logger.log(formObject[key]);
      Logger.log(typeof formObject[key]);
      Logger.log(columnValues);    
      var indexOfKey = columnValues.indexOf(formObject[key]);
      Logger.log(indexOfKey);
      var value = formObject[key];    //row[indexOfTimestamp]
      entity[key] = row[indexOfKey];
    }
  }
}

日志:

[17-06-15 15:48:02:071 PDT] lat 
[17-06-15 15:48:02:072 PDT] string
[17-06-15 15:48:02:072 PDT] [a, b, c, lat]
[17-06-15 15:48:02:073 PDT] -1.0

所以formObject [key]或值是lat。类型是一个字符串(到目前为止一切都很好)。该列看起来像[a,b,c,lat]。我基本上想要返回lat的索引,我认为应该是3。我正在努力与indexOfKey变量。我尝试的任何东西都返回-1,就像字符串不在数组中一样。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

这实际上是一个已知错误(there's a ticket for it in google's issue tracker)。

最简单的解决方法是将以下polyfill添加到您的代码中(sourced from MDN)。

tag_id