lastIndexOf混乱 [英] lastIndexOf Confusion
问题描述
我真的不明白lastIndexOf是如何工作的。我无法使用第二个可选参数。
I really dont understand how lastIndexOf works. I could not get the usage of second optional parameter.
string.lastIndexOf(searchvalue,start)
searchvalue - >必填。要搜索的字符串
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
有人可以一步一步地告诉我这个想法吗?为什么第一个返回-1而第二个返回2例如?
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
所以从1开始,我没有看到匹配。但是2,我看到 s
然后 s
at 3。
So starting at 1 and I dont see a match. But with 2, I see s
then s
at 3.
MDN explains it well.
这篇关于lastIndexOf混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!