【问题标题】:How to get the index of any array matching an exact text in Google Apps Script?如何获取与 Google Apps 脚本中的确切文本匹配的任何数组的索引?
【发布时间】:2021-09-03 20:06:16
【问题描述】:
如何在以下示例代码中获取任何具有“AAPL”的数组的索引?以下代码返回 true 或 false。而不是真或假,我怎样才能得到 0 和 2?感谢您的帮助!
function test() {
var tickers = [], isAAPL = [];
tickers[0] = 'AAPL';
tickers[1] = 'GOOG';
tickers[2] = 'AAPL';
tickers[3] = 'MSFT';
// how to find the index of the array containing 'AAPL'? The output should be 0 and 2.
isAAPL = tickers.map(x => (x == 'AAPL'));
console.log(isAAPL);
}
【问题讨论】:
标签:
arrays
google-apps-script
【解决方案1】:
function test() {
let tickers = ['AAPL', 'GOOG', 'AAPL', 'MSFT'];
let found = [];
let start = '';
var idx = '';
do {
idx = tickers.indexOf('AAPL', start);
if (~idx) {
found.push(idx);
start = idx + 1;
}
} while (~idx)
console.log(found.join(','));
}
Execution log
2:25:24 PM Notice Execution started
2:25:25 PM Info 0,2
2:25:25 PM Notice Execution completed
这也有效:
function test1() {
var tickers = [], isAAPL = [];
tickers[0] = 'AAPL';
tickers[1] = 'GOOG';
tickers[2] = 'AAPL';
tickers[3] = 'MSFT';
// how to find the index of the array containing 'AAPL'? The output should be 0 and 2.
isAAPL = tickers.map((x,i) => {if(x == 'AAPL')return i;}).filter(e => !isNaN(e) );
console.log(isAAPL.join(','));
}
【解决方案2】:
这是另一种方法 - 库珀回答中的第一种方法略有不同:
var tickers = ['AAPL', 'GOOG', 'AAPL', 'MSFT'];
var symbol = 'AAPL';
var idx = tickers.indexOf(symbol);
var isAAPL = [];
while (idx != -1) {
isAAPL.push(idx);
idx = tickers.indexOf(symbol, idx + 1);
}
console.log(isAAPL);
这在循环中使用indexOf() 重复查找“下一个”事件。
每次从找到字符串的最后一个位置之后的位置开始。