[英]indexOf in google script
我正在嘗試在 google 腳本中的對象上使用 findIndex() 但它不起作用。 這是一個例子:
function myFunction() {
var searchingJohn = "John";
var DATA = {namesList: []};
DATA.namesList.push({name: "John", otherDataForThisName: []});
var result = DATA.namesList.findIndex(function (element)
{return element.name == this;}, searchingJohn);
return result;
}
這在 javascript consol 中運行良好,但谷歌腳本返回給我一個“TypeError: Fonction findIndex not found in object .....”
你不能。
您正在嘗試在對象上使用findIndex()
,但findIndex()
用於數組。
從關於findIndex()
的 MDN 文檔:
findIndex() 方法返回數組中滿足提供的測試函數的第一個元素的索引。 否則返回-1。
原因是對象不以任何特定順序保存鍵值對。 例如,
{key1:value1, key2:value2}
和
{key2:value2, key1:value1}
是完全相同的對象。 所以找不到索引。
這是使用findIndex()
函數在 google 腳本中搜索對象中的字符串的示例。 例子:
function myFunction() {
var DATA = {namesList: []};
DATA.namesList.push({name: "John", otherDataForThisName: []});
DATA.namesList.push({name: "Mark", otherDataForThisName: []});
DATA.namesList.push({name: "Twin", otherDataForThisName: []});
const searching = "Mark";
var result = DATA.namesList.findIndex(function (element){
return element.name.toLowerCase() == searching.toLowerCase();
});
return result;
}
findIndex()
函數也用於二維數組。
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cellRange = ss.getRange("B5:Q10").getValues();
var someString = "John";
if (cellRange == "John")
{
//Do this code.
}
這是我能想到的提取您想要獲取的信息的唯一方法。 IndexOf(); 如果“John”在數組中,則從索引中提取,它看起來像這樣 ["J", "o", "h", "n"] 這就是為什么不能以這種方式找到它的原因。
上面的代碼將在一系列單元格中找到它,您可以完成整個工作表,但添加到其中的“空”越多,運行速度就越慢。 如果您需要檢查大量工作表,另一個嵌套的 if 循環可以為您清理。
我在使用 gscript 的許多基本 javascript 功能上遇到了同樣的問題,我在腳本的頂部添加了 polyfill,它可以與許多功能一起使用。
將此代碼粘貼到腳本的頂部,它將支持 indexOf。
// This version tries to optimize by only checking for "in" when looking for undefined and
// skipping the definitely fruitless NaN search. Other parts are merely cosmetic conciseness.
// Whether it is actually faster remains to be seen.
if (!Array.prototype.indexOf)
Array.prototype.indexOf = (function(Object, max, min) {
"use strict"
return function indexOf(member, fromIndex) {
if (this === null || this === undefined)
throw TypeError("Array.prototype.indexOf called on null or undefined")
var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len)
if (i < 0) i = max(0, Len + i)
else if (i >= Len) return -1
if (member === void 0) { // undefined
for (; i !== Len; ++i) if (that[i] === void 0 && i in that) return i
} else if (member !== member) { // NaN
return -1 // Since NaN !== NaN, it will never be found. Fast-path it.
} else // all else
for (; i !== Len; ++i) if (that[i] === member) return i
return -1 // if the value was not found, then return -1
}
})(Object, Math.max, Math.min)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.