JS includes() 返回部分匹配。

huangapple go评论63阅读模式
英文:

JS includes() returning partial matches

问题

Sure, here is the translated code part:

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

问题出现在数组中较大的数字上如果列表包含34则输出仅显示tourid为34的详细信息但如果列表中包含134则输出显示tourid为34和134的详细信息我还尝试了indexOf()并获得了类似的结果

是否有一种方法可以强制includes()仅进行精确匹配

以下是脚本是的它在工作线程脚本中因此以postMessage结尾):

function getMyLst(mylst) {
  // 根据myList数组构建导航列表

  // 检查mylst是否为空或没有数字
  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);
        // 循环检查是否在mylst中,然后构建字符串
        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();

  }
}

工作线程onmessage函数mylst作为逗号分隔的字符串发送到工作线程的值

onmessage = function (e) {

  // 从第一个变量中确定工作线程函数
  // 在“|”之前去掉第一个值
  let msg = e.data[0];
  var val = msg.split('|');

  // 获取myList数据
  if (val[0] === 'mylst') {
    var mylst = val[1] ;
    getMyLst(mylst);
  }
  // myList部分结束
}

Please note that I've retained the code structure and variable names in the translation.

英文:

I have a string of numbers which we are comparing to ids in a JSON file with javascript to create a list of favorites. I am using includes() to test if the tourid in the JSON file is also in the string.

The issue shows up with larger numbers in the array. If the list contains 34, then the output shows only the details for tourid 34, but if 134 is in the list, then the output shows both tourid 34 and 134. I have also tried indexOf() with similar results.

Is there a way to force includes() to only go with exact matches?

The script is below (and yes it is in a worker script hence the postMessage ending):

function getMyLst(mylst) {
// build nav list based on myList array
// check if mylst is empty of numbers
if (mylst === &#39;&#39;) {
let myLstStr = &#39;rmvml|0&#39;;
postMessage(myLstStr);
}
else {
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 &amp;&amp; this.status == 200) {
var myLstStr = &#39;mylst|&#39;;
var lstCnt = 0;
var daLst = &#39;&#39;;
var clipList = &#39;&#39;;
data = JSON.parse(this.responseText);
// loop through check if in mylst then build string
for (let i = 0; i &lt; data.length; i++) {
if (mylst.includes(data[i].tourid)) {
myLstStr += &#39;&lt;a href=&quot;&#39;+data[i].url+&#39;&quot;&gt;&#39;+data[i].tourname+&#39;&lt;/a&gt;&lt;br&gt;&#39;;
lstCnt++;
daLst += (data[i].tourid)+&#39;,&#39;;
clipList += data[i].tourname+&#39; - &#39;+data[i].url+&#39;\n&#39;;
}
}
myLstStr += &#39;|&#39;+lstCnt+&#39;|&#39;+daLst.slice(0, -1)+&#39;|&#39;+clipList;
postMessage(myLstStr);
} 
};
xmlhttp.open(&quot;GET&quot;, dturl, true);
xmlhttp.send();
}
}

The worker onmessage function, with the value of mylst as sent to the worker as a comma separated string: mylst|146,57,134

onmessage = function (e) {
// Determine worker function from first variable
// strip first value before &quot;|&quot;
let msg = e.data[0];
var val = msg.split(&#39;|&#39;);
// GO get myList data
if (val[0] === &#39;mylst&#39;) {
var mylst = val[1] ;
getMyLst(mylst);
}
// end myList section

答案1

得分: 2

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

为了使includes()仅搜索完全匹配的项,您可以通过使用**===**运算符来比较值来更新您的代码。

if(mylst.includes(data[i].tourid))这行替换为
if(mylst.split('&#39;,&#39;).includes(data[i].tourid.toString())),这将确保在值之间进行完全匹配。这里,split()用于将逗号分隔的字符串转换为数组,而toString()用于确保进行字符串比较。

解决方案:

function getMyLst(mylst) {
 // 根据myList数组创建导航列表

 // 在这里检查mylst是否为空或为数字
 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);
    // 循环检查是否在mylst中,然后构建字符串
    for (let i = 0; i < data.length; i++) {
      if (mylst.split('&#39;,&#39;).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();

}
}

希望这对您有所帮助,如果有问题,请随时告诉我 JS includes() 返回部分匹配。

英文:

The above issue that you are facing is occurring because the includes() method in JavaScript searches for the substring in the string, which means it will find matches not only for exact matches but also for partial matches.

To make includes() for only to search for exact matches, you can update your code to compare the values using the === operator instead.

Replace the line if(mylst.includes(data[i].tourid)) with
if(mylst.split(&#39;,&#39;).includes(data[i].tourid.toString())) and it will ensure a exact match between values. Here, split() is used to convert the comma-separated string to an array, and toString() is used to ensure a string comparison.

solution:

function getMyLst(mylst) {
// create nav list based on myList array
// here check if mylst is empty of numbers
if (mylst === &#39;&#39;) {
let myLstStr = &#39;rmvml|0&#39;;
postMessage(myLstStr);
}
else {
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 &amp;&amp; this.status == 200) {
var myLstStr = &#39;mylst|&#39;;
var lstCnt = 0;
var daLst = &#39;&#39;;
var clipList = &#39;&#39;;
data = JSON.parse(this.responseText);
// loop through check if in mylst then build string
for (let i = 0; i &lt; data.length; i++) {
if (mylst.split(&#39;,&#39;).includes(data[i].tourid.toString())) {
myLstStr += &#39;&lt;a href=&quot;&#39;+data[i].url+&#39;&quot;&gt;&#39;+data[i].tourname+&#39;&lt;/a&gt;&lt;br&gt;&#39;;
lstCnt++;
daLst += (data[i].tourid)+&#39;,&#39;;
clipList += data[i].tourname+&#39; - &#39;+data[i].url+&#39;\n&#39;;
}
}
myLstStr += &#39;|&#39;+lstCnt+&#39;|&#39;+daLst.slice(0, -1)+&#39;|&#39;+clipList;
postMessage(myLstStr);
} 
};
xmlhttp.open(&quot;GET&quot;, dturl, true);
xmlhttp.send();

}
}

I hope this work fine for you and if its not kindly let me know JS includes() 返回部分匹配。

答案2

得分: 1

使用 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);
  }
}
英文:

use string.search() method instead

it can differ the 34 from 134 and find only the unique also accept the regexp

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const sampledata = [
{
id:34
},
{
id:134
},
{
id:234
}
];
let mylst = &#39;146,57,134,34&#39;;
for (let i = 0; i &lt; sampledata.length; i++) {
const includes = mylst.search(sampledata[i].id)&gt;0?true:false;
if (includes) {
//do something
console.log(&#39;I am in&#39;,sampledata[i].id)
}else{
console.log(&#39;I am not present&#39;,sampledata[i].id)
}
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月11日 13:58:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定