a-b*_*rge 10 google-sheets google-apps-script
我正在使用range.getValues()Google Apps脚本加载数组.
var array = SpreadsheetApp.getActive().getActivesheet().getRange('E10:E30').getValues();
> array = [["val1"],["val2"],["val3"],["val4"]]
Run Code Online (Sandbox Code Playgroud)
然后我想循环遍历一个单独的列表,看看它的元素是否存在于数组中,使用array.prototype.includes():
if(array.includes("val4")) {doSomething;}
Run Code Online (Sandbox Code Playgroud)
像这样使用array.prototype.includes()有两个原因:1)因为每个元素array本身就是一个数组而2)因为该方法在Google Apps脚本中不可用:
TypeError:找不到包含在对象中的函数
然后想使用array.prototype.flat()来解决1)但似乎它在Google Apps脚本中也不可用.我收到以下错误:
TypeError:无法在对象中找到平坦的函数
这是我可以用蛮力做的事情,但肯定有一种巧妙的方法吗?
Dim*_*gns 11
最简单的解决方案Array.prototype.includes是在您的应用程序脚本项目中使用MDN中的以下polyfill.只需创建一个脚本文件并粘贴以下代码 - 代码/ polyfill将直接将函数添加到Array原型对象:
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function(searchElement, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If len is 0, return false.
if (len === 0) {
return false;
}
// 4. Let n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0;
// 5. If n ? 0, then
// a. Let k be n.
// 6. Else n < 0,
// a. Let k be len + n.
// b. If k < 0, let k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}
// 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
if (sameValueZero(o[k], searchElement)) {
return true;
}
// c. Increase k by 1.
k++;
}
// 8. Return false
return false;
}
});
}
Run Code Online (Sandbox Code Playgroud)
对于array.prototype.includesMDN站点,还提供了替代解决方案.其中一个利用array.prototype.flat和array.prototype.reduce:
替换.includes()用.indexOf()+1(它会产生0如果元素不存在,否则它会产生与您的阵列的长度1之间的整数)。它适用于谷歌脚本。
if(array.indexOf("val4")+1) {doSomething;}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7956 次 |
| 最近记录: |