在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 妈妈生日祝福语简短励志