-
Notifications
You must be signed in to change notification settings - Fork 634
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
编程题:用最简洁代码实现 indexOf 方法 #58
Comments
str.indexOf(searchValue [, fromIndex])
参考出处:indexOf() 解法一,正则function indexOf(str, a, start = 0) {
if(start<0) start+=str.length;
if(start>=str.length) return -1;
const reg = new RegExp(`${a}`, 'gi')
reg.lastIndex = start
const result = reg.exec(str)
return result ? result.index : -1
} 解法二,遍历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.slice(i, i+a.length) == a) return i;
}
return -1;
} |
遍历的时候不应该是 |
@597796340 如果 |
日复一日默写代码 |
说错了,应该是说如果a是单字符的话就不对,indexOf('abcd', 'cd') |
@597796340 哈哈哈哈明白了。应该是 |
let str = 'hello world ,I am ok';
/**
* 正则方法实现
* @param {*} searchStr
* @param {*} start
* @returns
*/
String.prototype.myindexOf=function(searchStr, start=0){
if (start < 0) start += this.length
if (start >= this.length) return -1
const reg = new RegExp(`${searchStr}`, 'ig')
reg.lastIndex = start//确定匹配起始位置
let res = reg.exec(this)
return res ? res.index : -1
}
console.log(str.myindexOf('world',7))
/**
* 2. 遍历字符串
*/
String.prototype._indexOf = function(searchStr,start=0) {
if(start<0) start+=this.length
if(start>this.length-1) return -1
for(let i=start;i<this.length;i++) {
if(this.slice(i,i+searchStr.length)===searchStr) return i
}
return -1
}
console.log(str._indexOf('I')) |
正则方法随便写两个就是错的,不要误人子弟 sIndexOf('sss\^asdsad', '^')
0
'sss\^asdsad'.indexOf('^')
3
sIndexOf('sss$asdsad', '$')
10
'sss$asdsad'.indexOf('$')
3
sIndexOf('sss[$asdsad', '[')
Uncaught SyntaxError: Invalid regular expression: /[/: Unterminated character class
'sss[$asdsad'.indexOf('[')
3 |
indexOf
有两种:返回从
fromIndex
处开始搜索第一次出现的指定值的索引,如果未找到,返回-1
返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回
-1
解答
String.prototype.indexOf()
解题思路:正则,字符串匹配
测试成功
Array.prototype.indexOf()
解题思路:遍历匹配
测试成功
总结一下
你也可以尝试使用遍历匹配法解决
sIndexOf
问题(正则更简洁),这里不做介绍(和aIndexOf
差不多的套路,不同的是,String
类型可以一次匹配多个字符)The text was updated successfully, but these errors were encountered: