小写和大写是相同的JS

时间:2017-12-07 01:45:14

标签: javascript arrays object

我正在创建一个程序,它将拉出字符串中第一个不重复的单词。在这样做时,我遇到了一个逻辑问题,我需要用大写和小写来计算一个单词,但仍然返回字符串的原始大写版本。

这是我的代码:

function firstNonRepeatingLetter(str) {
 // split the array and transform it to lowercase
 str = str.split('');

 // create an obj that will hold the counter of each characters
 let myObj = {};

 // create a new arr for all the char w/ 1 value
 let uniq = [];

 // iterate through the splitted array
 str.forEach((char) => {
    // if the obj contains the same key (char)
   if(myObj.hasOwnProperty(char)){
      // we add 1 to its value
     myObj[char]++;
   }else{
      // otherwise we set the key value to 1 
     myObj[char] = 1;
   }
 });

 // check the obj with 1 value, 
 for(let prop in myObj){
  // and then push the key inside a 
   // new arr with only 1 counter
   if(myObj[prop] === 1){
     uniq.push(prop);
   }
 }

 console.log(myObj);

 // return the first elem in the arr
 return uniq.length !== 0 ? uniq[0] : '';
}

firstNonRepeatingLetter('sTress') // => must return 'T' instead return 't'
firstNonRepeatingLetter('NecEssarY') // => must return 'N' instead return 'n'

对象看起来像这样:{ N: 1, e: 1, c: 1, E: 1, s: 2, a: 1, r: 1, Y: 1 }它计算的是' N'和' n分开。

知道如何在不影响功能的情况下保留实际案例吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

首先想到的方法是将对象属性名称转换为大写,以便计算" A"和" a"在一起,但除了存储计数存储的第一个发现的情况。所以在你现有的循环中:

   let upperChar = char.toUpperCase();
   if(myObj.hasOwnProperty(upperChar)){
     myObj[upperChar].count++;                     // add 1 to its count
   } else {
     myObj[upperChar] = { first: char, count: 1 }; // otherwise set count to 1
   }

在完整代码的上下文中:



function firstNonRepeatingLetter(str) {
 str = str.split('');

 let myObj = {};
 let uniq = [];

 str.forEach((char) => {
    // if the obj contains the same key (char)
   let upperChar = char.toUpperCase();
   if(myObj.hasOwnProperty(upperChar)){         
     myObj[upperChar].count++;                     // add 1 to its count
   }else{ 
     myObj[upperChar] = { first: char, count: 1 }; // otherwise set count to 1
   }
 });

  
 for(let prop in myObj){              // check the obj with 1 value,       
   if(myObj[prop].count === 1){       // and then push the key inside a 
     uniq.push(myObj[prop].first);    // new arr with only 1 counter
   }
 }

 console.log(myObj);

 return uniq.length !== 0 ? uniq[0] : ''; // return the first elem in the arr
}

console.log(firstNonRepeatingLetter('sTress')); // => must return 'T' 
console.log(firstNonRepeatingLetter('NecEssarY')); // => must return 'N'
console.log(firstNonRepeatingLetter('Stress')); // => must return 't' 




答案 1 :(得分:0)

我建议你首先将字符串的所有字符转换为小写或大写。

var res = str.toLowerCase();

这样它就不会分别计算角色。