Why does IndexOf return -1?

若如初见. 提交于 2019-11-26 22:54:02

问题


I am learning Javascript and don't understand why the indexOf below returns -1:

var string = "The quick brown fox jumps over the lazy dog";

console.log (string.indexOf("good"));

回答1:


-1 means "no match found".

The reason it returns -1 instead of "false" is that a needle at the beginning of the string would be at position 0, which is equivalent to false in Javascript. So returning -1 ensures that you know there is not actually a match.




回答2:


-1 means no match found. "good" is not in that sentence. This is documented behaviour.

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.




回答3:


Because arrays are 0 based, returning 0 would mean starting from the first character was matched; 1, the second character, and so on. This means anything 0 and up would be a true or "found" response. To keep everything in the integer category, -1 signifies no match found.




回答4:


There is another reason for indexOf to return -1 when no match is found. Consider the code below:

if (~str.indexOf(pattern)){
  console.log('found')
}else{
  console.log('not found')
}

Because ~(-1) = 0 so the fact that indexOf returning -1 makes it easier to write if...else using ~.




回答5:


The search never finds what it's looking for ("good" isn't in the sentence), and -1 is the default return value.

http://www.w3schools.com/jsref/jsref_indexof.asp



来源:https://stackoverflow.com/questions/8585897/why-does-indexof-return-1

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