Last active
July 23, 2017 07:04
-
-
Save black-black-cat/ee69b1b1606c83379969e90404cd7038 to your computer and use it in GitHub Desktop.
匹配关键词在字符串中各处出现的位置的索引,组成数组。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 循环 | |
let find = (str, keyword) => { | |
let i = 0, arr = [] | |
let index = 0 | |
while (true) { | |
index = str.indexOf(keyword, i) | |
if (index == -1) break | |
arr.push(index) | |
i = index + 1 | |
} | |
return arr | |
} | |
// 递归 | |
function indexes(string, str) { | |
var ret = [] | |
var from = 0 | |
var isFin = false | |
function inner (string, str) { | |
var index = string.indexOf(str, from) | |
if ( index > -1 ) { | |
ret.push(index) | |
from = index + 1 | |
inner(string, str) | |
} | |
} | |
inner(string, str) | |
return ret | |
} | |
indexOf('1010', '0') // -> [1, 3] | |
// 尾递归 | |
function indexOf(string, str) { | |
var ret = [] | |
var from = 0 | |
var isFin = false | |
function inner (string, str) { | |
var index = string.indexOf(str, from) | |
if ( index > -1 ) { | |
ret.push(index) | |
from = index + 1 | |
return inner(string, str) | |
} else { | |
return ret | |
} | |
} | |
return inner(string, str) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment