You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionsIndexOf(str,searchStr,fromIndex=0){varregex=newRegExp(`${searchStr}`,'ig')regex.lastIndex=fromIndexvarresult=regex.exec(str)returnresult ? result.index : -1}// 测试varparagraph='The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?'varsearchTerm='dog'// 测试一:不设置 fromIndexconsole.log(sIndexOf(paragraph,searchTerm))// 40console.log(paragraph.indexOf(searchTerm));// 40// 测试二:设置 fromIndexconsole.log(sIndexOf(paragraph,searchTerm,41))// 52console.log(paragraph.indexOf(searchTerm,41));// 52
日复一日默写代码
function indexOf(str, a, start = 0) {
if (start < 0) {
start += str.length;
}
if (start >= str.length) return -1;
for (let i = start, len = str.length; i < len; i++) {
if (str[i] === a) { return i; }
}
return -1;
}
Activity
plane-hjh commentedon Jun 2, 2020
str.indexOf(searchValue [, fromIndex])
searchValue:要被查找的字符串值,默认undefinedfromIndex: 可选值。数字表示开始查找的位置。可以是任意整数,默认值为 0。如果fromIndex的值小于 0,或者大于 str.length ,那么查找分别从 0 和str.length 开始。参考出处:indexOf()
解法一,正则
解法二,遍历
JerryWen1994 commentedon Jun 2, 2020
遍历的时候不应该是
if (str[i] == a) return i;,如果a是字符串的话就不对了,应该是if (str.slice(i, i+a.length) == a) return i;plane-hjh commentedon Jun 2, 2020
@597796340 如果
a是字符串的话就不对了。这个a是字符串为什么不对,方便解释一下吗0undefined0 commentedon Jun 2, 2020
日复一日默写代码
function indexOf(str, a, start = 0) {
if (start < 0) {
start += str.length;
}
if (start >= str.length) return -1;
for (let i = start, len = str.length; i < len; i++) {
if (str[i] === a) { return i; }
}
return -1;
}
JerryWen1994 commentedon Jun 2, 2020
说错了,应该是说如果a是单字符的话就不对,indexOf('abcd', 'cd')
plane-hjh commentedon Jun 2, 2020
@597796340 哈哈哈哈明白了。应该是
a是多字符的时候。多谢指出哈,已经修改啦xllpiupiu commentedon Oct 2, 2021
eeve commentedon Nov 17, 2021
正则方法随便写两个就是错的,不要误人子弟