返回字符串中第一个重复字符的索引-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 教师闺蜜祝福语简短