【问题标题】:Javascript problems when converting a string to an array and then back again将字符串转换为数组然后再返回时出现 Javascript 问题
【发布时间】:2015-08-11 11:32:47
【问题描述】:

我正在尝试解决 Codewars 上的 Javascript 挑战。

等值线是一个没有重复字母的单词,连续的或不连续的。实现一个函数,该函数确定仅包含字母的字符串是否为等值线。假设空字符串是等值线。忽略字母大小写。

isIsogram( "Dermatoglyphics" ) == true
isIsogram( "aba" ) == false
isIsogram( "moOse" ) == false // -- ignore letter case

我的努力如下:

    function isIsogram(str) {
    var arr = str.split("");
    var seen = {};
    var out = [];
    var length = arr.length;
    var j = 0;
    for(var i = 0; i < length; i++) {
         var item = arr[i].toLowerCase;
         if(seen[item] !== 1) {
               seen[item] = 1;
               out[j++] = item;
         }
    }
    console.log(out.toString.toLowerCase);
    console.log(str.toLowerCase);
    if (out.toString.toLowercase === str.toLowerCase) {
     return true;
    }
    else {
      return false;
    }
}

在代码战中我的结果

console.log(out.toString.toLowerCase); is undefined 

的结果
console.log(str.toLowerCase); is [Function: toLowerCase].

这意味着我的解决方案总是评估为假。

如果能帮助我指出正确的方向或突出我的错误,而不是为我提供解决方案,我将不胜感激,这样我就可以更有效地学习。谢谢!

【问题讨论】:

    标签: javascript arrays string


    【解决方案1】:

    这可能是一个更简单的答案。

    function isIsogram(str){
    
      // Turn all letters of the string to lower case and split it into an array. 
    
      var letters = str.toLowerCase().split('');
      var checkLetters = [];
      
      /* Check to see if the letter appears in the checkLetters array.
         If the letter is not already in the array it will push the letter into it. */
    
      letters.forEach(function(letter) {
        if(checkLetters.indexOf(letter) === -1) {
          checkLetters.push(letter);
        }
      });
    
      /* Now we have two arrays. If the letters array has non-duplicate letters then 
         it will be the same length as the checkLetters array. If not, the checkLetters array
         will be shorter. */
    
      /* Return true or false depending on whether the lengths of both arrays are equal */
        
      return letters.length === checkLetters.length ? true : false;
    
    }

    【讨论】:

      【解决方案2】:

      toStringtoLowerCase 是函数。在Javascript中,要执行一个函数,你必须在函数名的末尾加上括号:

      out.toString().toLowerCase()
      //          ^^            ^^
      

      您需要为所有功能执行此操作:

      arr[i].toLowerCase()
      
      str.toLowerCase
      
      out.toString.toLowercase() === str.toLowerCase()
      

      (请注意,在数组上调用 .toString() 将包含逗号,例如 "a,b,c,d,e"。对于这个用例可能无关紧要,但只是为了强调这一点)

      【讨论】:

        【解决方案3】:

        toString 和 toLowerCase 等是函数

        使用:

        out.toString().toLowerCase()
        

        但是,对于 out,我想你想做 out.join('').toLowerCase()

        【讨论】:

          【解决方案4】:

          我认为您可以通过使用 hashmap 系统和every 方法以功能方式进行改进。

          every 方法对数组中存在的每个元素执行一次提供的回调函数,直到找到一个回调函数返回一个假值

          所以,你的代码会更干净。

            function isIsogram(str) {
              //Create our hashmap
              var hashmap = {};
              //Return value of 'every' loop
              return str.split("").every(function(elm){
                //If our hashmap get current letter as key
                return hashmap.hasOwnProperty(elm.toLowerCase())
                //Return false, str is not an Isogram
                ? false
                //Otherwise, set letter as key in our hashmap,
                //we can check the next iteration
                : hashmap[elm.toLowerCase()] = true;
              });
            }
          
          console.log(isIsogram('Dermatoglyphics'));
          console.log(isIsogram('moOse'));
          console.log(isIsogram('aba'));
          

          【讨论】:

            【解决方案5】:

            我知道你已经解决了这个问题,但只是为了多样化。 通过忽略大小写,首先将输入更改为小写。

            function isIsogram(str) {
                 // Change word to lower case
                str = str.toLowerCase();
                  // split the word into letters and store as an array
                var arr = str.split("");
                  // get the length so the array can be looped through
                var len = arr.length;
                  // an array to contain letters that has been visited
                var seen = []
                for (var i = 0; i < len; i++) {
                    // check if letter has not been visited by checking for the index
                  if(seen.indexOf(arr[i])<0){
                     // if the letter doesn't exist,add it to seen and go to next letter
                    seen.push(arr[i]);
                  }else{
                     // if letter exists, the word is not an isogram return false
                    return false
                  }
                }
                   // the loop is complete but each letter appeared once, the word is an isogram
               return true
            }
            
            console.log(isIsogram('Dermatoglyphics'));
            console.log(isIsogram('moOse'));
            console.log(isIsogram('aba'));
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2023-02-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-12-18
              • 1970-01-01
              • 1970-01-01
              • 2021-08-16
              相关资源
              最近更新 更多