gpt4 book ai didi

javascript - 如何在 Javascript 字符串对象中使用 lastIndexOf() 方法的第二个参数?

转载 作者:行者123 更新时间:2023-11-30 18:36:46 24 4
gpt4 key购买 nike

"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也有一个可选的第二个参数,它是从哪里开始搜索的索引值,从右数开始,所以字符串'apple ' 应该匹配位置 5。但我仍然得到 -1 的结果?

有什么问题?

最佳答案

lastIndexOf 的语法是:

string.lastIndexOf(searchValue[, fromIndex])

其中 fromIndex 是可选的,代表开始查找的索引。但是,搜索是向后执行的,因此在您的示例中从位置 3 开始搜索字符串 "This";

关于javascript - 如何在 Javascript 字符串对象中使用 lastIndexOf() 方法的第二个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8018190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com