在JavaScript中查找字符串的第一个非重复字符
我们需要编写一个JavaScript函数,该函数将字符串作为第一个也是唯一的参数。
该函数应该找到并返回它在字符串中遇到的第一个字符的索引,该字符串在字符串中仅出现一次。
如果字符串不包含任何唯一字符,则函数应返回-1。
例如-
如果输入字符串是-
const str = 'hellohe';
那么输出应该是-
const output = 4;
示例
以下是代码-
const str = 'hellohe';
const firstUnique = (str = '') => {
let obj = {};
for(let i = 0; i < str.length; i++){
if(str[i] in obj){
let temp = obj[str[i]];
let x = parseInt(temp[0]);
x += 1;
temp[0] = x;
obj[str[i]] = temp;
} else {
obj[str[i]] = [1, i]
}
}
let arr = Object.keys(obj);
for(let i = 0; i < arr.length; i++){
let z = obj[arr[i]]
if(z[0] === 1){
return z[1];
}
}
return -1;
};
console.log(firstUnique(str));输出结果以下是控制台输出-
4
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语