-
Notifications
You must be signed in to change notification settings - Fork 3.3k
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
第 151 题:用最简洁代码实现indexOf方法 #321
Comments
字符串变为数组,用数组方法findIndex去查找。 |
Object.prototype.sIndexOf = function (char) {
const len = this.length
for (let i = 0; i < len; i++) {
if (this[i] === char) {
return i
}
}
return -1
} |
|
能使用其它数组api? const indexOf = (arr, val) => {
return arr.findIndex(item => item === val);
} |
这题考点在哪啊,没盖特到 ,难道是有什么特别6的写法吗 |
|
看了一圈怎么没人考虑indexOf的第二个起始参数呢? |
function indexOf(arr,target,start=0){
if(start<0) start+=arr.length;
if(start>=arr.length) return -1;
for(let i=start;i<arr.length;++i){
if(arr[i]===target) return i;
}
return -1;
} |
|
function indexOf(str, serchStr, index) { |
Array.prototype.myIndexOf = function(item, start = 0) { |
因为大家都不咋用这个参数,想不起来了呗 |
|
|
|
@ghost2113 substr应该换成substring吧 |
|
|
function _indexOf(string, target) {
if (typeof string !== 'string') {
throw new Error('string only');
}
let mt = string.match(new RegExp(target))
return mt ? mt.index : -1;
} |
使用正则 indexOf('/:>-|+?','/:>-|+?') 这个测试用例应该通不过 |
indexOf 字符串,数组也能用吧, function indexOfTest(arrOrString, target, index = 0) {
if(Array.isArray(arrOrString)) {
for(let i = index; i < arrOrString.length; i++) {
if(arrOrString[i] == target) {
return i
}
}
return -1;
}
// 字符串
const newArr = arrOrString.split(target);
if(newArr.length == 1) {
return -1
}
let res = 0;
for(let j = 0; j < newArr.length; j++) {
if(newArr[j] == "" && index == 0) {
return 0
}
if(res > index) {
return res;
}
res += newArr[j].length || 1;
}
return res;
} |
function formatIndexof(str, target, index) {
let begin = index || 0;
let end = str.length || 0;
const tLen = target.length
if (begin > end) {
return -1;
}
if (tLen == 1 || Object.prototype.toString.call(str) === '[object Array]') {
for (let i = begin; i < end; i++) {
if (str[i] === target) {
return i
}
}
} else if (tLen > 1) {
for (let i = begin; i < end; i++) {
const temp = str.slice(i, tLen + i);
if (target === temp) {
return i
}
}
}
return -1;
} |
|
|
好像没说是数组还是字符的indexOf function arrayIndexOf (array = [], item) {
for (let i = 0; i < array.length; i++) {
if (array[i] === item) {
return i;
}
}
return -1;
}
function stringIndexOf (str = '', subStr) {
if (!subStr) return -1;
for (let i = 0; i < str.length; i++) {
if (str.substr(i, subStr.length) === subStr) {
return i;
}
}
return -1;
} |
for循环 这题好像没什么考的意义哦 |
function mockIndexOf(eles, target, startIndex = 0) {
const dataType = Object.prototype.toString.call(eles);
if (dataType === '[object Array]') {
const len = eles.length;
const _startIndex = startIndex >= 0 ? startIndex : startIndex + len;
return eles.findIndex((v, index) => {
return _startIndex <= index && v === target;
});
}
if (dataType === '[object String]') {
const len = eles.length;
const _startIndex =
startIndex >= 0 ? (startIndex < len ? startIndex : len) : 0;
const result = eles.substr(_startIndex).match(target);
console.log(result, eles.substr(startIndex), target);
return result ? result.index + _startIndex : -1;
}
throw new Error('第一个参数请传入数组或者字符串');
}
mockIndexOf('dsafsa', 'sa')' // 1
mockIndexOf('dsafsa', 'sf')' // -1 |
|
兼容实现字符串和数组的 indexOf,针对字符串处理方式不一样:
|
/**
* 字符串
* @param str
* @param target
* @param start
* @returns {number|*}
*/
function strIndexOf(str, target, start = 0){
if (start > str.length) {
return -1;
}
if (start < 0) {
start = 0;
}
for (let i = start; i < str.length; i++) {
let current = str.substring(i, i + target.length);
if (current === target) {
return i;
}
}
return -1;
} |
function indexOf(a, b){
var index = a.split(b)[0].length;
return index === a.length ? -1 : index;
}
var a = 'abcbbcddc';
var b = 'bb';
indexOf(a, b); // 3
indexOf(a, '1'); // -1 |
// 使用startsWith
function indexOf(src: string, slice: string): number {
const _indexOf = (src: string, slice: string, index: number): number => {
if (slice.length === 0 || src.length < slice.length) return -1
return src.startsWith(slice) ? index : _indexOf(src.slice(1), slice, index + 1)
}
return _indexOf(src, slice, 0)
}
// 循环版本
function indexOf2(src: string, slice: string): number {
for (let i = 0; i < src.length && (src.length - i) >= slice.length; ++i) {
if (src.startsWith(slice, i)) return i
}
return -1;
}
const a = 'abcdefghijkl'
const b = 'ghi'
const c = '123'
console.log(indexOf(a, b)) // 6
console.log(indexOf(a, c)) // -1 |
'123'.search(x) |
先说下思路吧,比较笨,哈哈
function findIndex(key, obj) {
console.log(`查找的对象${obj}`, `----查找的键值${key}`)
let arr = []
let index = -1 //最后返回查找到的索引
/**********************如果是数组***********************/
if (obj instanceof Array) {
arr = obj
arr.some((i, indexA) => {
if (i == key) {
index = indexA
return true
}
})
}
/**********************如果是字符串***********************/
else if (typeof (obj) === 'string') {
arr = obj.split('')
let keyLen = key.length
for(let i=0;i<=arr.length-keyLen;i++){
if(key === obj.substring(i, i+keyLen)){
index = i
}
}
} else {
return '不符合数据格式'
}
return index
}
console.log(31, findIndex('g', 'abcdefg'))
console.log(32, findIndex(22, [22,33,444])) |
实现/**
*
* @param {string} p
*/
function buildNext(p) {
const m = p.length
const N = []
let t = N[0] = -1
let j = 0
while (j < m -1) {
if (0 > t || p[j] === p[t]) {
j++
t++
// 根据已知信息如果p[j] !== t[i] 如果p[j] === p[t]则p[t]必然失配t[i]所以这次比较可以优化
N[j] = p[j] !== p[t] ? t : N[t]
} else {
t = N[t]
}
}
return N
}
/**
* kmp字符串模式匹配
* @param {string} t
* @param {string} p
*/
function match(t, p) {
let N = buildNext(p)
let i = 0
let j = 0
const n = t.length
const m = p.length
while(j < m && i < n) {
if (0 > j || t[i] === p[j]) {
i++
j++
} else {
j = N[j]
}
}
return j === m ? i - j : -1
}
export function indexOf(s, fromIndex = 0) {
fromIndex = 0 > fromIndex
? this.length + fromIndex > 0
? this.length + fromIndex
: 0
: fromIndex
console.log(fromIndex)
const i = match(this.slice(fromIndex), s)
return i > 0 ? fromIndex + i : i
} 测试import { indexOf} from '@/dayily-interview/kmp'
describe('kmp.js', () => {
it('match success',() => {
expect(indexOf.call('test success', 'c')).toBe(7)
})
it('match fail',() => {
expect(indexOf.call('test success', 'z')).toBe(-1)
})
it('match success with from index', () => {
expect(indexOf.call('test success', 's', 3)).toBe(5)
})
it('match fail with from index', () => {
expect(indexOf.call('test success', 't', 4)).toBe(-1)
})
it('match success with complex', () => {
expect(indexOf.call('test success', 'ucce', 3)).toBe(6)
})
it('match with negative from index', () => {
expect(indexOf.call('test success', 'ucce', -16)).toBe(6)
})
it('match with negative from index', () => {
expect(indexOf.call('test success', 'ss', -1)).toBe(-1)
})
it('match with negative from index', () => {
expect(indexOf.call('test success', 'ss', -2)).toBe(10)
})
it('match with zero from index', () => {
expect(indexOf.call('test success', 'ss', 0)).toBe(10)
})
}) |
思路一: 利用正则比对当前字符串找出位置 |
class myString extends String {
myIndexOf(str: string) {
const O = Object(this);
const reg = new RegExp(str, 'g');
const res = reg.exec(O);
if (res) {
return res.index;
}
return -1;
}
}
const stringTest = new myString('abcdefg');
console.log(stringTest.myIndexOf('23'));
console.log(stringTest.myIndexOf('cde'));
export {}; |
不通过 |
//js 实现indexof
Array.prototype._indexOf=function(res,fromIndex){
let len = this.length;
if(len === 0) return [];
if(fromIndex > len){
fromIndex = len;
}
if(fromIndex <= 0){
fromIndex = 0
}
for(let i = fromIndex; i < len; i++){
if(this[i] === res){
return i;
}
}
return -1;
} |
|
看了下评论区发现,此题说用最简单代码实现,故意误导了大家往简单的想... /**
* @param {*} item
* @param {Number} fromIndex
*/
function indexOf(item, fromIndex = 0) {
if (fromIndex < 0) fromIndex = 0
if (fromIndex >= this.length) return -1
for (let i = fromIndex; i < this.length; i += 1) {
if (Array.isArray(this)) {
if (this[i] === item) return i
} else if (typeof this === 'string') {
for (let j = i; j < this.length; j += 1) {
const sub = this.substring(i, j + 1)
if (sub === item) return i
}
}
}
return -1
}
// eslint-disable-next-line no-extend-native
Array.prototype.myIndexOf = indexOf
// eslint-disable-next-line no-extend-native
String.prototype.myIndexOf = indexOf
/**
* test
*/
const arrRes = ['q', 'w', 'e', 'r'].myIndexOf('e', 1)
console.log('arrRes: ', arrRes)
const strRes = 'abcdefgkdeg'.myIndexOf('deg')
console.log('strRes: ', strRes) |
|
String.prototype.indexOf = function (search, fromIndex = 0) {
if (fromIndex < 0) fromIndex = 0;
if (fromIndex >= this.length) return -1;
let str = this;
let reg = RegExp(`(?<=.{${fromIndex}})(${search})`);
let result = reg.exec(str);
return result ? result.index : -1;
}; |
数组,感觉这题是考indexOf的定义,fromIndex的各种取值对结果的影响 Array.prototype.indexOf = function (search, fromIndex = 0) {
const arrLen = this.length;
if (fromIndex >= arrLen) return -1;
if (fromIndex < 0) {
fromIndex = arrLen + fromIndex;
}
for (let i = fromIndex; i < arrLen; i++) {
if (i < 0) {
i = 0;
continue;
}
if (search == this[i]) {
return i;
}
}
return -1;
}; |
function myIndexOf(source, target, start = 0) {
if (Array.isArray(source)) {
let res = -1;
for (let i = start; i < source.length; i++) {
if (source[i] === target) return res = i;
}
}
if (typeof source === 'string') {
const reg = new RegExp(target, 'g');
reg.lastIndex = start;
const result = reg.exec(source);
return result ? result.index : -1;
}
} |
Array.prototype._indexOf = function (val, start) {
if (typeof start !== "number") start = 0; //start 非数字
if (start < 0) start = start + this.length //start 小于零
const index = this.slice(start).findIndex((item) => item === val);
return index > -1 ? index + start : -1
}
String.prototype._indexOf = function (val, start) {
if (typeof start !== "number") start = 0;
start = Math.min(Math.max(0, start), this.length) // start大于等于0小于字符串的长度
if (val === '') return start; // val为空字符串返回开始的位置
const reg = new RegExp(val);
const res = this.slice(start).match(reg);
return res ? res.index + start : -1
} |
String.prototype._indexOf = function (val, start) {
if (typeof start !== "number") start = 0; // start非数字
start = Math.min(Math.max(0, start), this.length) // start大于等于0小于字符串的长度
if (val === '') return start; // val为空字符串返回开始的位置
const arr = this.slice(start).split(val);
return arr.length >= 2 ? arr[0].length + start : -1 // 分割后的数组大于2就说存在,并且第一个值的长度加开始位置就是val的index
} |
indexof如果像楼上们那样写的话,速度太慢了,最简单的就是直接用indexof,如果是要实现他,当然是用kmp算法,速度最快。 |
|
const NOT_INCLUDE = -1; String.prototype.indexOf = function(string, start = 0) { Array.prototype.indexOf = function(item, start = 0) {
} |
Array.prototype._indexOf = function (searchElement, fromIndex = 0) {
if (typeof fromIndex !== 'number') {
fromIndex = 0;
}
if (fromIndex < 0) {
fromIndex += this.length;
}
for (let i = fromIndex; i < this.length; i++) {
if (this[i] === searchElement) return i;
}
return -1;
}; |
|
function indexOf(self, target, startIdx = 0) {
if (startIdx >= self.length) return -1;
let _startIdx = startIdx;
const isArray = Array.isArray(self);
if (_startIdx < 0) {
_startIdx = isArray ? Math.max(0, _startIdx + self.length) : 0;
}
if (isArray) {
for (let i = _startIdx; i < self.length; i++) {
if (self[i] === target) return i;
}
return -1;
}
const regex = new RegExp(target, 'ig');
regex.lastIndex = _startIdx;
return regex.exec(self)?.index ?? -1
} |
const a = "abcdefg", b = "efg";
const diff = a.length - b.length;
for (let i = 0; i <= diff; i++) {
if (a.slice(i, i + b.length) === b) {
return i;
}
}
return -1; |
function indexOf(target, value, start = 0) {
let t = target.slice(start);
let index = -1;
if(t instanceof Array) {
for(let i in t) {
if(t[i] === value) {
index = parseInt(i);
break;
}
}
} else {
const reg = new RegExp(`${value}`);
index = t.match(reg).index;
}
return index > -1 ? index + start : -1;
} |
The text was updated successfully, but these errors were encountered: