定义一个函数,lettersAfter,接受三个参数:
haystack:要搜索的字符串
needle:要搜索的字符。
limit:要返回的字符后的字母数
lettersAfter 应该返回第一个找到的搜索字符出现后的字母。返回的字母应限制为第三个参数的数量。
例如:
lettersAfter('hello', 'e', 2);
// => ll
lettersAfter('hello', 'h', 1);
// => e
lettersAfter('indefatigable', 'a', 4);
// => tiga
这是我的代码:
function lettersAfter(haystack, needle, limit) {
let letters = ''
for (i = 0; i < haystack.length; i++) {
if (needle === haystack[i]) {
for (j = 0; j < limit; j++) {
letters += haystack[i + j + 1];
}
}
}
return letters;
}
console.log(lettersAfter('Bobthebuilder', 'b', 5));
根据提示,代码应该返回'thebu',但最终返回'thebuuilde'。有什么建议吗?
另一种选择是使用
indexOf
找到您的“针”并使用找到的索引(如果有的话)和限制来确定 substring
返回。在下面的代码中,indexOf 用于查找索引,并向该索引添加 1,因为我们需要needle
之后的字母。然后我们检查是否 firstIndex > 0
因为如果没有找到索引,indexOf 返回 -1,但是因为我们添加了 1,所以现在为 0。如果条件为真,从 firstIndex 中取出一个子字符串并检查剩余长度是否更小超过极限。我为条件为 false 添加了一个 return 语句,以表明没有找到索引。
注意:如果
needle
可以超过1个字母/字符,则在为+1
赋值时需要将+needle.length
更改为firstIndex
。
function lettersAfter(haystack, needle, limit) {
if ((firstIndex = haystack.indexOf(needle) + 1) > 0) {
return haystack.substring(firstIndex,
haystack.length - firstIndex < limit
? haystack.length
: (firstIndex + limit));
} else {
return `Needle '${needle}' could not be found!`;
}
}
console.log(lettersAfter('Bobthebuilder', 'b', 5))
问题是,在第一次找到该字符后,循环继续进行,如果第二次找到相同的字符,则会向
letters
添加更多内容。要解决此问题,break
在您第一次找到它后退出循环:
function lettersAfter(haystack, needle, limit) {
let letters = '';
for (let i = 0; i < haystack.length; i++) {
if (needle === haystack[i]) {
for (let j = 0; j < limit; j++) {
letters += haystack[i + j + 1];
}
break; // break out of the loop after first occurance is found
}
}
return letters;
}
console.log(lettersAfter('Bobthebuilder', 'b', 5));
然而,在现实世界中,最好只使用内置函数
.indexOf()
和.substring()
:
function lettersAfter(haystack, needle, limit) {
const index = haystack.indexOf(needle);
return haystack.substring(index+1, index+limit+1);
}
console.log(lettersAfter('Bobthebuilder', 'b', 5));