返回字符串中第一个重复字符的索引-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 祝福语对联文案简短大气