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

如何让JavaScript includes()方法对ID字符串执行精确匹配?

如何让JavaScript实现ID的精确匹配?

我需要对比逗号分隔的数字ID字符串与JSON数据中的tourid,生成收藏列表。当前用includes()判断时出现误匹配:当列表包含134时,tourid为34的项也会被选中,而我需要精确匹配ID。indexOf()也有同样问题。

问题原因

includes()是字符串的子串匹配方法,34是"134"的子串,所以会被误判为存在。要实现精确匹配,应该把ID字符串转换为数组或集合,再进行元素级别的判断。

解决方案

将逗号分隔的ID字符串转为数组(或Set),利用数组的includes()(或Set的has())做精确匹配:

修改后的核心代码

function getMyLst(mylst) {
  if (mylst === '') {
    let myLstStr = 'rmvml|0';
    postMessage(myLstStr);
  } else {
    // 将ID字符串转为Set,提升查找效率(数据量大时更明显)
    const idSet = new Set(mylst.split(',').map(id => id.trim()));

    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        var myLstStr = 'mylst|';
        var lstCnt = 0;
        var daLst = '';
        var clipList = '';
        const data = JSON.parse(this.responseText);
        
        for (let i = 0; i < data.length; i++) {
          // 将tourid转为字符串,与Set中的字符串ID精确匹配
          if (idSet.has(data[i].tourid.toString())) {
            myLstStr += `<a href="${data[i].url}">${data[i].tourname}</a><br>`;
            lstCnt++;
            daLst += `${data[i].tourid},`;
            clipList += `${data[i].tourname} - ${data[i].url}\n`;
          }
        }
        myLstStr += `|${lstCnt}|${daLst.slice(0, -1)}|${clipList}`;
        postMessage(myLstStr);
      }
    };

    xmlhttp.open("GET", dturl, true);
    xmlhttp.send();
  }
}

说明

  1. 转Set的优势:Set的has()方法查找时间复杂度为O(1),比数组includes()的O(n)更高效,适合处理大量ID的场景。
  2. 类型统一:将tourid转为字符串,确保与ID集合中的元素类型一致,避免因数字/字符串类型差异导致的匹配失败。
  3. 处理空格:用trim()处理ID字符串中可能存在的空格,避免因空格导致的匹配错误。

如果数据量较小,也可以用数组替代Set:

const idArray = mylst.split(',').map(id => id.trim());
// 循环中判断
if (idArray.includes(data[i].tourid.toString())) {
  // ...
}

内容的提问来源于stack exchange,提问作者MrCycling

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:17:33