Skip to content

编程题:用最简洁代码实现 indexOf 方法 #58

Description

@sisterAn

indexOf 有两种:

String.prototype.indexOf()

返回从 fromIndex 处开始搜索第一次出现的指定值的索引,如果未找到,返回 -1

str.indexOf(searchValue[,fromIndex])// fromIndex 默认值为 0

Array.prototype.indexOf()

返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回 -1

arr.indexOf(searchElement[,fromIndex])

解答

String.prototype.indexOf()

解题思路:正则,字符串匹配

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

测试成功

Array.prototype.indexOf()

解题思路:遍历匹配

functionaIndexOf(arr,elem,fromIndex=0){if(!elem)return-1for(leti=fromIndex;i<arr.length;i++){if(arr[i]===elem)returni}return-1}// 测试varbeasts=['ant','bison','camel','duck','bison']// 测试一:不设置 fromIndexconsole.log(aIndexOf(beasts,'bison'))// 1console.log(beasts.indexOf('bison'))// 1// 测试二:设置 fromIndexconsole.log(aIndexOf(beasts,'bison',2))// 4console.log(beasts.indexOf('bison',2))// 4

测试成功

总结一下
functionindexOf(items,item,fromIndex=0){letisArray=Array.isArray(items);letisString=Object.prototype.toString.call(items)=='[object String]';if(!isArray&&!isString)thrownewSyntaxError();if(isArray)returnsIndexOf(items,item,fromIndex)elsereturnaIndexOf(items,item,fromIndex)}

你也可以尝试使用遍历匹配法解决 sIndexOf 问题(正则更简洁),这里不做介绍(和 aIndexOf 差不多的套路,不同的是,String 类型可以一次匹配多个字符)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions