Javascript 如何检查:数组是否正确包含特定文本?
我正在努力做一个数组搜索,其中包含一段必须包含反斜杠的文本。我试过Javascript 如何检查:数组是否正确包含特定文本?,javascript,arrays,string,indexof,Javascript,Arrays,String,Indexof,我正在努力做一个数组搜索,其中包含一段必须包含反斜杠的文本。我试过包含(“”)否定包括(“”)并使用索引(“”)尝试类似操作 我有一个简单的数组,最多有四个值;通常它有两个,下面是它的典型外观: {tks: Array(2)} tks: Array(2) 0: "https://mycoolwebsite.net/arcgis/rest/services" 1: "https://mycoolwebsite.com/arcgis/rest/services"
包含(“”)代码>否定<代码>包括(“”)
并使用索引(“”)
尝试类似操作
我有一个简单的数组,最多有四个值;通常它有两个,下面是它的典型外观:
{tks: Array(2)}
tks: Array(2)
0: "https://mycoolwebsite.net/arcgis/rest/services"
1: "https://mycoolwebsite.com/arcgis/rest/services"
length: 2
__proto__: Array(0)
__proto__: Object
下面是我正在尝试做的简单检查:我对*的第二次检查包括*
'wdt'
文本似乎工作得很好,我想这是因为反斜杠。无论如何,我可以处理这个问题?我很困惑,为什么我的if
和else
都会在下面使用反斜杠的第一次检查中被击中。。。我在else上添加了否定项以进行双重检查。。无论在else
中有无该选项,都会点击else
// right before doing the search I am building the array, just to add more context
for (let i = 0; i < coolObj.length; i++) {
if (coolObj[i].url){
tr = coolObj[i].url;
tks.push(tr);
console.log({tks});
}
}
console.log({tks}); // consoles as I have included above ^
if (tks.includes('/arcgis/rest/services')) {
console.log({tks});
} else if (!tks.includes('/arcgis/rest/services')) {
console.log({tks});
console.log('does not include correct url');
aT = '/arcgis/rest/services';
lP = false;
filterAt(aT);
}
if (tks.includes('wdt')) {
console.log({tks});
}else {
console.log({tks});
wT = 'wdt';
filterWt(wT);
}
//在执行搜索之前,我正在构建数组,只是为了添加更多上下文
for(设i=0;i
来自:includes()方法确定数组的条目中是否包含某个值,并根据需要返回true或false
必须使用String.prototype.includes
在数组元素中测试字符串,因此:
const arr=[”https://mycoolwebsite.net/arcgis/rest/services", "https://mycoolwebsite.com/arcgis/rest/services"];
arr.forEach(el=>{
if(el.includes('/arcgis/rest/services')){
log(el':包括url');
}
否则{
log('不包括正确的url');
}
如果(包括('wdt')){
控制台日志(el’:包括wdt’);
}否则{
console.log('不包括正确的wdt');
}
});代码>您仅对整个值进行比较,。。你们中没有人将完整的url与https://...
etc在它们中,IOW:您的包含内容都不会返回真值。哇。。。那么我该如何实现“包含”特定文本呢?您需要循环数组,并检查每个数组项。