查找字符串中的字母距离 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/12 11:24:17
我们需要编写一个 JavaScript 函数,该函数将一个字符串作为第一个参数和两个单元素字符串。该函数应返回作为第一个参数的字符串中这些单字母字符串之间的距离。
例如 −
如果三个字符串是 −
const str = 'Disaster management'; const a = 'i', b = 't';
然后输出应该是 4,因为 'i' 和 't' 之间的距离是 4
示例
以下是代码 −
const str = 'Disaster management';
const a = 'i', b = 't';
const distanceBetween = (str, a, b) => {
const aIndex = str.indexOf(a);
const bIndex = str.indexOf(b);
if(aIndex === -1 || b === -1){
return false;
};
return Math.abs(aIndex - bIndex);
};
console.log(distanceBetween(str, a, b));
输出
以下是控制台中的输出 −
4
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

