"This apple is my apple".lastIndexOf("apple"); // returns value of 17
"This apple is my apple".lastIndexOf("apple",12); // returns value of 5
"This apple is my apple".lastIndexOf("apple", 3); // returns value of -1, not found嗨,伙计们!
我理解前两个例子,但是为什么第三个不返回5呢?
和indexOf一样,苹果也有一个可选的第二个参数,这个参数是从右边开始搜索的索引值,所以字符串‘lastIndexOf’应该匹配位置5,但是我还是得到了-1?
有什么问题吗?
发布于 2011-11-05 12:32:26
lastIndexOf的语法为:
string.lastIndexOf(searchValue[, fromIndex])其中fromIndex是可选的,表示开始查找的索引。但是,搜索是从后向字符串执行的,所以在示例中从位置3开始将通过"This"进行搜索;
发布于 2011-11-05 12:32:54
搜索是向后进行的。因此,如果" start“是3,它将从第四个字符开始并向后工作。这意味着它只会从s中的"This“中搜索,然后向后搜索,而不会包含"apple”。
发布于 2018-05-19 02:32:52
这里,它是'5‘。然后,计数将从左到右开始,即从单词“heck”开始。现在,它将从字母"h“倒数到空格、字母"t”、"a“、"h”和"w“。希望它能大做文章。如果你把'4‘放在'5’的位置,它会输出'-1‘,因为它会从空格到字母"t“再到"a”,然后就没有"heck“这个词了。
var st = 'What heck the heck',
index = st.lastIndexOf('heck', 5);
//It goes backward from the number you assigned it https://stackoverflow.com/questions/8018190
复制相似问题