以下是眼前的任务:
“编写一个名为
stringLastIndexOf
的函数,它接受两个字符串:第一个是单词,第二个是单个字符。 函数应该返回字符存在的最后一个索引,如果找不到字符,则返回-1。 不要使用内置的String.lastIndexOf()
函数!“
我特别地为结束需求而挣扎,这就是让我的函数返回str2字符所在的确切位置。在不使用lastindexof
函数的情况下,我能做些什么呢?
function stringLastIndexOf(str1, str2) {
var pos = str1.includes(str2, -1);
if (pos !== true) {
return -1;
} else {
return str2.position();
}
}
console.log(
stringLastIndexOf('word', 'w'),
stringLastIndexOf('pumped', 'f')
);
发布于 2019-12-28 04:58:00
简单的for循环可以解决您的问题。
function stringLastIndexOf(str1, str2) {
let index = -1
for (var i = 0; i < str1.length; i++) {
if (str1[i] === str2) {
index = i
}
}
return index
}
console.log(
stringLastIndexOf('word', 'w'),
stringLastIndexOf('pumped', 'f')
);
发布于 2019-12-28 04:53:58
您可以向后循环:
const aLastIndexOf = (str, ch) => {
for (let index = str.length - 1; index >= 0; index--) {
if (str[index] == ch)
return index;
}
return -1;
}
举个例子:
const aLastIndexOf = (str, ch) => {
for (let index = str.length - 1; index >= 0; index--) {
if (str[index] == ch)
return index;
}
return -1;
}
console.log(aLastIndexOf("hello", 'h'));
console.log(aLastIndexOf("hello", 'l'));
console.log(aLastIndexOf("hello", 'e'));
发布于 2019-12-28 04:52:09
如果首先反转字符串,则只需使用indexOf
function stringLastIndexOf(str, c) {
let pos = str.split("").reverse().join("").indexOf(c);
return pos == -1 ? -1 : str.length - pos;
}
请注意,通过使用split
将字符串转换为一个字符数组,反转该数组,并使用join
将该数组再次加入到字符串中,该字符串将被反转。
indexOf
的结果必须从原始字符串的长度中减去。
https://stackoverflow.com/questions/59511022
复制相似问题