英文:
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 === '') {
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();
}
}
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 "|"
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
答案1
得分: 2
上述问题是由于JavaScript中的includes()方法在字符串中搜索子字符串,这意味着它不仅会找到完全匹配的项,还会找到部分匹配的项。
为了使includes()仅搜索完全匹配的项,您可以通过使用**===**运算符来比较值来更新您的代码。
将if(mylst.includes(data[i].tourid))
这行替换为
if(mylst.split('',').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('',').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();
}
}
希望这对您有所帮助,如果有问题,请随时告诉我
英文:
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(',').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 === '') {
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();
}
}
I hope this work fine for you and if its not kindly let me know
答案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 = '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)
}
}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论