javascript - LastIndexOf() 函数的替代方案

标签 javascript indexof

这是手头的任务:

"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/

相关文章:

javascript - 如何按顺序合并两个数组?

javascript - Css 重置为小于 320px

vb.net - 如何使用子字符串查找空格来显示首字母

javascript - javascript indexOf 不区分大小写

javascript - npm init 中的 "entry point"是什么

c# - 使用 Javascript 加密并使用 C# 解密的简单算法

javascript - 停止影响子 child 的 Jquery nth-child

c# - 在字符串中的两个值之间查找单词

java - 为什么在这段代码中我不能让 indexOf() 等于 0 以外的任何值?

java - 获取数组列表中项目的索引;