我们需要编写一个JavaScript函数,该函数接受一个字符串并返回出现在字符串中两次的第一个字符的索引。
如果没有这样的字符,那么我们应该返回-1。
为此的代码将是-
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