在JavaScript中查找字符串中第一个重复字符的索引
我们需要编写一个JavaScript函数,该函数接受一个字符串并返回出现在字符串中两次的第一个字符的索引。如果没有这样的字符,那么我们应该返回-1。
假设以下是我们的字符串-
const str = 'Hello world, how are you';
我们需要找到第一个重复字符的索引。
示例
为此的代码将是-
const str = 'Hello world, how are you';
const firstRepeating = str => {
const map = new Map();
for(let i = 0; i < str.length; i++){
if(map.has(str[i])){
return map.get(str[i]);
};
map.set(str[i], i);
};
return -1;
};
console.log(firstRepeating(str));输出结果
控制台中的输出将为-
2
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿