JS includes() 返回部分匹配

问题描述 投票:0回答:2

我有一串数字,我们正在使用 javascript 将其与 json 文件中的 id 进行比较,以创建收藏夹列表。我正在使用 includes() 来测试 json 文件中的 tourid 是否也在字符串中。

问题出现在数组中更大的数字。如果列表包含 34,则输出仅显示 tourid 34 的详细信息,但如果列表中包含 134,则输出同时显示 tourid 34 和 134。我也尝试过 indexOf() 并得到类似的结果。

有没有办法强制 includes() 只使用精确匹配?

脚本在下面(是的,它在工作脚本中,因此 postMessage 结束):

function getMyLst(mylst) {
  // build nav list of based on myList array

  // check if mylst is empty of numbers
  if (mylst === '') {
    let myLstStr = 'rmvml|0';
    postMessage(myLstStr);
  }
  else {

    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        var myLstStr = 'mylst|';
        var lstCnt = 0;
        var daLst = '';
        var clipList = '';
        data = JSON.parse(this.responseText);
        // loop through check if in mylst then build string
        for (let i = 0; i < data.length; i++) {
          if (mylst.includes(data[i].tourid)) {
            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();

  }
}

worker onmessage 函数,将 mylst 的值作为逗号分隔的字符串发送给 worker:mylst|146,57,134

onmessage = function (e) {

  // Determine worker function from first variable
  // strip first value before "|"
  let msg = e.data[0];
  var val = msg.split('|');

  // GO get myList data
  if (val[0] === 'mylst') {
    var mylst = val[1] ;
    getMyLst(mylst);
  }
  // end myList section
javascript arrays include
2个回答
1
投票

出现上述问题是因为 JavaScript 中的 includes() 方法搜索字符串中的substring,这意味着它不仅会找到完全匹配的匹配项,还会找到部分匹配项。

要使 includes() 仅用于搜索完全匹配项,您可以更新代码以使用 === 运算符来比较值。

将 if (mylst.includes(data[i].tourid)) { 替换为 if (mylst.split(',').includes(data[i].tourid.toString())) { 它将确保值之间的精确匹配。这里,split() 用于将逗号分隔的字符串转换为数组,toString() 用于确保字符串比较。

解决方案:

function getMyLst(mylst) {
 // create nav list based on myList array

 // here check if mylst is empty of numbers
 if (mylst === '') {
  let myLstStr = 'rmvml|0';
  postMessage(myLstStr);
 }
 else {

let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
    var myLstStr = 'mylst|';
    var lstCnt = 0;
    var daLst = '';
    var clipList = '';
    data = JSON.parse(this.responseText);
    // loop through check if in mylst then build string
    for (let i = 0; i < data.length; i++) {
      if (mylst.split(',').includes(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();

} }

我希望这对你有用,如果不方便请告诉我 :)


0
投票

使用 string.search() 方法代替

它可以区分 34 和 134,并且只找到唯一的也接受 regexp

const sampledata = [
  {
    id:34
  },
  {
    id:134
  },
  {
    id:234
  }
];

let mylst = '146,57,134,34';


for (let i = 0; i < sampledata.length; i++) {
  const includes = mylst.search(sampledata[i].id)>0?true:false;
  if (includes) {
    //do something
    console.log('I am in',sampledata[i].id)
  }else{
    console.log('I am not present',sampledata[i].id)
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.