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,就好像该字符串不在数组中一样。有什么建议吗?
最佳答案
这实际上是一个已知错误 ( there's a ticket for it in google's issue tracker )。
最简单的解决方法是将以下填充添加到您的代码中 ( sourced from MDN )。
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let o be the result of calling ToObject passing
// the this value as the argument.
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of o with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = o.length >>> 0;
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = fromIndex | 0;
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of o with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of o with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in o && o[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
关于javascript - 如何使用谷歌应用脚本获取数组中值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44578208/