【问题标题】:How javascript indexOf works differently with string and array?javascript indexOf 与字符串和数组的工作方式有何不同?
【发布时间】:2014-10-11 10:27:10
【问题描述】:

我有字符串和字符串数组。

var strFruit = "Apple is good for health";  
var arrayFruit = ["Apple is good for health"]; 

var strResult = strFruit.indexOf("Apple"); //strResult shows 0  
var arrayResult =  arrayFruit.indexOf("Apple"); // arrayResult  shows -1  

但如果我使用arrayFruit.indexOf("Apple is good for health") arrayResult 显示 0。

我的问题是为什么 indexOf 在 Array 元素中寻找完全匹配而不是在字符串中 以及两者的搜索有何不同?

Jsfiddle

PS:问这个问题的主要原因是我无法理解indexOf 的源代码。我可以理解它的作用(indexOf什么字符串和数组。但我不确定 如何 使用字符串和数组?(poly fills or source code)。

【问题讨论】:

    标签: javascript jquery arrays string indexof


    【解决方案1】:

    在数组中搜索时,indexOf 会尝试搜索整个字符串。例如:

    var arrayFruit = ["Apple", "is", "good", "for", "health"]; 
    var arrayResult =  arrayFruit.indexOf("Apple"); // arrayResult will be 0
    

    在您的情况下,数组中只有一项,即代表"Apple is good for health" 的字符串。所以indexOf 尝试将"Apple" 与它匹配。自:

    "Apple is good for health" != "Apple" 
    

    你得到-1 作为答案。如果你搜索整个字符串,它会给你0

    var arrayResult =  arrayFruit.indexOf("Apple is good for health"); /arrayResult will be 0
    

    【讨论】:

      【解决方案2】:

      在字符串中使用 indexOf 时,它会在字符串中搜索您传递给它的参数。另一方面,在数组上使用它时,它会在数组中搜索该元素。

      字符串:

      var myString = "Apple is good for health";
      console.log("Apple is at", myString.indexOf("Apple"));
      //Outputs "Apple is at 0"
      

      数组:

      var myArray = ["Apple is good for health", "Another sentence", "Sentence 3"];
      console.log("Apple is good for health is element", myArray .indexOf("Apple is good for health"));
      //Outputs "Apple is good for health is element 0"
      console.log("Sentence 3 is at", myArray.indexOf("Sentence 3"));
      //Outputs "Sentence 3 is at 2"
      

      【讨论】:

        【解决方案3】:

        strFruit.indexOf("Apple")strFruit 中搜索字符串Apple,但arrayFruit.indexOf("Apple") 在数组中搜索值为Apple 的项目

        【讨论】:

          【解决方案4】:

          如果您为 array 对象调用 indexOf,它会将全文与每个元素进行比较,因此在您的情况下,您将单个单词与完整句子(这是数组中的唯一元素)进行比较,返回 @987654323 @,那很好。但如果你这样做,

          var k = "Apple is good for health".split(" ");
          var idx = k.indexOf("Apple"); // it will return 0
          

          【讨论】:

            【解决方案5】:

            在arrayFruit中你有一个字符串对象,为了比较它应该匹配result= 0的同一个对象

            在 strFruit 中你有字符序列,它将这些字符序列与 indexOf 匹配

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-05-25
              • 1970-01-01
              • 2011-09-09
              • 2018-07-22
              • 2011-06-13
              • 2014-02-09
              相关资源
              最近更新 更多