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

标签 javascript arrays prototype indexof

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

通常这就是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

但是在句子数组中,值就像让我们早上联系基地看看我们在哪里indexOf实际上返回true,即使它只是部分的该短语的内容与陈词滥调的值相匹配。

这是如何工作的?

最佳答案

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

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

示例:

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

关于javascript - indexOf 如何返回这个例子的位置,结果不应该是-1吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35235150/

相关文章:

javascript - 如果 Javascript 的原生 OOP 是无类的,那么构造函数呢?这不是意味着一个类吗?

javascript - .css() 会自动添加 vendor 前缀吗?

javascript切换显示/隐藏div

javascript - 访问 iFrame 中的数据属性?

java - 使用分而治之的 Maxsub 数组

javascript - JavaScript 中的对象原型(prototype)

javascript - 如何在具体情况下停止隐藏下拉内容?

c - 表达式必须具有指向对象的指针类型

arrays - Swift 数组中的 AnyType 错误

javascript - oop 行为类似于构造函数参数类型的类