lastIndexOf Confusion

被刻印的时光 ゝ 提交于 2019-12-07 17:10:45

问题


I really dont understand how lastIndexOf works. I could not get the usage of second optional parameter.

string.lastIndexOf(searchvalue,start)

searchvalue -> Required. The string to search for

start -> Optional. The position where to start the search. If omitted, the default value is the length of the string

var test = "mississippi";

test.lastIndexOf("ss",1) // return -1
test.lastIndexOf("ss",2) // returns 2
test.lastIndexOf("ss",5) // returns 5

Could anyone tell me the idea step by step ? Why first one returns -1 and second one returns 2 for example ?

TIA


回答1:


Its because thats the starting index. -1 means not found.

m 0
i 1
s 2
s 3
i 4
s 5
s 6
i 7
p 8
p 9
i 10

So starting at 1 and I dont see a match. But with 2, I see s then s at 3.

MDN explains it well.




回答2:


The lastIndexOf() method gets the last index of a search string in the main string. It takes one parameters as input a search string.

It returns the the last position (index) of the search string. If the search string can not be found it will return "-1". Visit http://skillcram.com/JS.htm for example



来源:https://stackoverflow.com/questions/12430291/lastindexof-confusion

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