indexOf 给出误报
indexOf gives false positives
我制作了一个函数来搜索给定字符串中的单词。名为 str_find
的函数接收单词,然后接收要搜索的参数。这些参数可以是一个包含字符串的数组,也可以只是一个字符串。
例如,如果我像这样调用函数:str_find("123456789&", ["", "123456789&"]);
它应该给我 true
,但出于罕见的原因有时它会给我 false
.
你能帮帮我吗?
我的代码:
function str_find(word, find){
if(!Array.isArray(find)){
if (word.indexOf(find) > 0) {
return true;
} else {
return false;
}
} else {
var flag = false;
for (var i = 0, length = find.length; i < length; i++) {
if (word.indexOf(find[i]) > 0) {
flag = true;
break;
}
}
return flag;
}
}
您可以利用具有 includes()
原型方法的字符串和数组
function str_find(needle, haystack) {
return haystack.includes(needle);
}
console.log(str_find("123456789&", ["", "123456789&"]))
console.log(str_find("foo", 'foobar'))
MDN points out 隐晦的原因:
Return value
The value of the first element in the array that satisfies the
provided testing function. Otherwise, undefined is returned.
当在搜索字符串的第一个位置找到字符串时,它 returns 找到的位置索引 0
- 这是一个虚假值:
因此,当发生这种情况时,您的逻辑测试 if (word.indexOf(find) > 0)
returns 为假,并给出未找到该字符串的错误指示,而实际上它是在搜索字符串的最开头找到的。
您可以通过测试 -1
而不是 > 0
来更改此行为。
或者,您可以选择使用其他不那么晦涩的 Array 方法。
const data = ["", "123456789&"];
const str = "123456789&";
const tests = ["4", "", "123456789&", ";", ["456", "123456789&"]];
function str_find(toFind, toSearch) {
let found = false;
if (!Array.isArray(toFind)) {
if (toSearch.indexOf(toFind) !== -1) {
found = true;
}
} else {
for (var i = 0; i < toFind.length; i++) {
found = str_find(toFind[i],toSearch);
}
}
return found;
}
tests.forEach(t=>console.log("test: ", t, str_find(t, data)));
我制作了一个函数来搜索给定字符串中的单词。名为 str_find
的函数接收单词,然后接收要搜索的参数。这些参数可以是一个包含字符串的数组,也可以只是一个字符串。
例如,如果我像这样调用函数:str_find("123456789&", ["", "123456789&"]);
它应该给我 true
,但出于罕见的原因有时它会给我 false
.
你能帮帮我吗?
我的代码:
function str_find(word, find){
if(!Array.isArray(find)){
if (word.indexOf(find) > 0) {
return true;
} else {
return false;
}
} else {
var flag = false;
for (var i = 0, length = find.length; i < length; i++) {
if (word.indexOf(find[i]) > 0) {
flag = true;
break;
}
}
return flag;
}
}
您可以利用具有 includes()
原型方法的字符串和数组
function str_find(needle, haystack) {
return haystack.includes(needle);
}
console.log(str_find("123456789&", ["", "123456789&"]))
console.log(str_find("foo", 'foobar'))
MDN points out 隐晦的原因:
Return value
The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
当在搜索字符串的第一个位置找到字符串时,它 returns 找到的位置索引 0
- 这是一个虚假值:
因此,当发生这种情况时,您的逻辑测试 if (word.indexOf(find) > 0)
returns 为假,并给出未找到该字符串的错误指示,而实际上它是在搜索字符串的最开头找到的。
您可以通过测试 -1
而不是 > 0
来更改此行为。
或者,您可以选择使用其他不那么晦涩的 Array 方法。
const data = ["", "123456789&"];
const str = "123456789&";
const tests = ["4", "", "123456789&", ";", ["456", "123456789&"]];
function str_find(toFind, toSearch) {
let found = false;
if (!Array.isArray(toFind)) {
if (toSearch.indexOf(toFind) !== -1) {
found = true;
}
} else {
for (var i = 0; i < toFind.length; i++) {
found = str_find(toFind[i],toSearch);
}
}
return found;
}
tests.forEach(t=>console.log("test: ", t, str_find(t, data)));