indexOf怎么返回这个例子的位置,结果不应该是-1吗?

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

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

通常这就是 indexOf return 的方式,正如预期的那样

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

这是我在一本书上看到的,但不明白为什么它 return 真的意味着它在数组中找到。

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 实际上 return 对这个来说是正确的,即使它只是短语的一部分匹配陈词滥调的值。

这是如何工作的?

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

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

示例:

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