How javascript indexOf works differently with string and array?

不问归期 提交于 2019-12-12 04:54:10

问题


I have both string and array of strings.

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  

But if i use arrayFruit.indexOf("Apple is good for health") arrayResult shows 0.

And my Question is why indexOf looks for exact match in Array element but not in string and how both search differ?.

Jsfiddle

P.S: Main reason to ask this question is i am unable to understand source code for indexOf.I can understand what it does(indexOf) with string and array.But im not sure how it is working with string and Array?(poly fills or source code).


回答1:


When searching in array, indexOf tries to search for entire string. For example:

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

In you your case, you have only one item in the array i.e. string representing "Apple is good for health". So indexOf tries to match "Apple" with it. Since:

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

you get -1 as answer. Had you searched for entire string, it would give you 0

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



回答2:


When using indexOf in a string, it searches the string for the argument that you passed it. On the other hand when using it on an array, it searches the array for that element.

String:

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

Array:

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") searches for string Apple in strFruit but arrayFruit.indexOf("Apple") searches for an item in array with the value Apple




回答4:


If you invoke indexOf for array object it will compare full text with each element , so in your case you are comparing a single word with full sentence ( which is the only element in array), which returns -1, and that is fine . But if you do like this,

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



回答5:


In arrayFruit you have one object of string and for comparing it shoud match the same object for result= 0

In strFruit you have sequence of characters, it matches these sequence of charachters with indexOf



来源:https://stackoverflow.com/questions/26313644/how-javascript-indexof-works-differently-with-string-and-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!