如何在TypeScript中检测数组元素的出现顺序
问题分析与解决
你的需求是判断数组中是否同时满足两个条件:
- 'two'出现在'finish'之前
- 'finish'之后也存在'two'
满足则返回checkFlag = true。
原代码的问题
你用Map存储元素和对应索引的方式存在缺陷:Map的键是唯一的,当同一个元素多次出现时,后面的索引会覆盖前面的。比如你的数组里'two'出现了3次,map.get('two')最终拿到的是最后一个'two'的索引(5),而'finish'的索引是2,5 < 2不成立,所以返回false,无法满足实际需求。
正确解法
先找到'finish'的位置,再分别检查它前后是否存在'two':
const empList = ['one', 'two', 'finish', 'one', 'two', 'two']; const finishIndex = empList.indexOf('finish'); let checkFlag = false; if (finishIndex !== -1) { // 检查finish之前是否有two const hasTwoBefore = empList.some((item, idx) => idx < finishIndex && item === 'two'); // 检查finish之后是否有two const hasTwoAfter = empList.some((item, idx) => idx > finishIndex && item === 'two'); checkFlag = hasTwoBefore && hasTwoAfter; } console.log(checkFlag); // 输出true
也可以用slice结合includes实现,逻辑更直观:
const empList = ['one', 'two', 'finish', 'one', 'two', 'two']; const finishIndex = empList.indexOf('finish'); const checkFlag = finishIndex !== -1 && empList.slice(0, finishIndex).includes('two') && empList.slice(finishIndex + 1).includes('two'); console.log(checkFlag); // 输出true
两种方法都能准确判断:先确认数组中存在'finish',再分别验证前后是否有'two',只有两个条件都满足时,checkFlag才为true。
内容的提问来源于stack exchange,提问作者Rjj
相关产品推荐
相关产品推荐

