javascript indexOf如何与字符串和数组不同地工作?

时间:2014-10-11 10:27:10

标签: javascript jquery arrays string indexof

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

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在数组元素中查找完全匹配但在字符串中查找完全匹配以及两者搜索有何不同?

Jsfiddle

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

5 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

在字符串中使用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"

答案 2 :(得分:1)

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

的项目

答案 3 :(得分:0)

在arrayFruit中,你有一个字符串对象,为了进行比较,它与result= 0

的同一对象匹配

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

答案 4 :(得分:0)

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

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