索引如何返回此示例的位置,结果不应该是 -1

How is indexOf returning the position of this example, shouldn't the result be -1?

本文关键字:位置 结果 不应该 何返回 返回 索引      更新时间:2023-09-26

我知道indexOf搜索字符串/数组中值的位置,然后返回位置,但我认为即使有空格,它也必须是完全匹配的。 但是我正在阅读这篇文章,我很困惑为什么即使比赛只是部分比赛,它也会返回真实。

通常这就是 indexOf 返回的方式,并且符合预期

var array = ["AA", "BB", "A", "CC", "D", "This is the time to be back home.", "It's christmas"];
// Let's say result >= 0 will return true else false
console.log(array.indexOf("AA") + " AA");   // 0 --true
console.log(array.indexOf("A") + " A");     // 2 --true
console.log(array.indexOf("C") + " C");     // -1 --false
console.log(array.indexOf("DD") + " DD");   // -1 --false
console.log(array.indexOf("the time") + " the time");   // -1 --false
console.log(array.indexOf("It's christmas") + " christmas");    // 6 --true

这是我在一本书中看到的,不明白为什么它会返回在数组中找到的真实含义。

String.prototype.cliche = function(){
    var cliche = ["lock and load", "touch base", "open the kimono"];
    for (var i = 0; i < cliche.length; i++){
        var index = this.indexOf(cliche[i]);
        if(index >= 0){
            return true;
        }
    }
    return false;
}
var sentences = ["I'll send my car around to pick you up.",
                "Let's touch base in the morning and see where we are",
                "We don't want to open the kimono, we just want to inform them."];
for(var i = 0; i < sentences.length; i++){
    var phrase = sentences[i];
    if(phrase.cliche()){
        console.log("CLICHE ALERT: " + phrase);
    }
}

函数中的陈词滥调数组只有部分短语,如touch base

但是在句子数组中,该值就像Let's touch base in the morning and see where we are indexOf实际上为此返回 true,即使它只是部分短语与陈词滥调的值匹配。

这是如何工作的?

那是因为它们是不同的方法:

  • Array.prototype.indexOf返回在数组中找到某个值(使用严格相等算法)的第一个位置。
  • String.prototype.indexOf返回字符串中包含某个字符串(是子字符串)的第一个位置。

例:

["AA"].indexOf("A"); // -1 (not found)
"AA".indexOf("A");   // 0