这是手头的任务:
"Write a function called
stringLastIndexOf
, which accepts two strings: the first is a word and the second is a single character.The function should return the last index at which the character exists or -1 if the character is not found.
Do not use the built in
String.lastIndexOf()
function!"
我特别在努力满足最终要求,即让我的函数返回 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')
);
最佳答案
您可以向后循环:
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'));
关于javascript - LastIndexOf() 函数的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59511022/