在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

猜你喜欢