返回字符串中第一个重复字符的索引-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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短