在Google Apps Script中如何获取数组内匹配精确文本的元素索引
解决方案
你可以通过遍历数组时同时获取索引和值的方式,直接收集匹配'AAPL'的元素索引,以下是几种常用实现:
方式1:使用reduce直接收集结果(最简洁)
function test() { var tickers = [], aaplIndexes = []; tickers[0] = 'AAPL'; tickers[1] = 'GOOG'; tickers[2] = 'AAPL'; tickers[3] = 'MSFT'; // 累积匹配的索引 aaplIndexes = tickers.reduce((result, currentValue, index) => { if (currentValue === 'AAPL') result.push(index); return result; }, []); console.log(aaplIndexes); // 输出:[0, 2] }
方式2:使用forEach遍历(更易理解)
function test() { var tickers = [], aaplIndexes = []; tickers[0] = 'AAPL'; tickers[1] = 'GOOG'; tickers[2] = 'AAPL'; tickers[3] = 'MSFT'; tickers.forEach((value, index) => { if (value === 'AAPL') { aaplIndexes.push(index); } }); console.log(aaplIndexes); // 输出:[0, 2] }
基于你原有代码的兼容写法
如果你不想改动原有map生成布尔数组的逻辑,可以对布尔数组做二次处理:
function test() { var tickers = [], isAAPL = []; tickers[0] = 'AAPL'; tickers[1] = 'GOOG'; tickers[2] = 'AAPL'; tickers[3] = 'MSFT'; isAAPL = tickers.map(x => (x == 'AAPL')); // 二次处理布尔数组,提取匹配的索引 const aaplIndexes = isAAPL .map((isMatch, index) => isMatch ? index : -1) .filter(index => index !== -1); console.log(aaplIndexes); // 输出:[0, 2] }
内容的提问来源于stack exchange,提问作者Newbie
相关产品推荐
相关产品推荐

