You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:00:53