javascript - Coderbyte 上的字母计数 I JavaScript 挑战

标签 javascript regex function loops object

我已经解决了这个问题几个小时,并且已经尽我所能,尽我所能解决这一挑战,但我无法确切地弄清楚了什么问题。我一直在这里遇到“意外的代币非法”:http://jsfiddle.net/6n8apjze/14/

和“typeError:无法读取null的属性'长度':http://goo.gl/LIz89F

我认为问题是Howmanyrepeat变量。我不明白为什么我得到它不会读取null的长度,而显然是str ...

的单词

我有一个想法:

word.toLowerCase().split("").sort().join("").match(/([.])\1+/g).length

...这里:Get duplicate characters count in a string

挑战:
使用JavaScript语言,具有函数LetterCounti(str)为Str 参数正在传递,并返回最大数量的第一个单词 重复的字母。例如:“今天,是有史以来最伟大的一天!”应该返回 最伟大的,因为它有2个E(和2 t),它也在 有 2 个 e。如果没有重复字母的单词,则返回 -1。言语将 被空间隔开。

function LetterCountI(str){
  var wordsAndAmount={};
  var mostRepeatLetters="-1";
  var words=str.split(" ");

     words.forEach(function(word){
       // returns value of how many repeated letters in word.
       var howManyRepeat=word.toLowerCase().split("").sort().join("").match(/([.])\1+/g).length;       
        // if there are repeats(at least one value).
        if(howManyRepeat !== null || howManyRepeat !== 0){ 
          wordsAndAmount[word] = howManyRepeat;
        }else{
         // if no words have repeats will return -1 after for in loop.
         wordsAndAmount[word] = -1; 
         }
     });

     // word is the key, wordsAndAmount[word] is the value of word.
     for(var word in wordsAndAmount){ 
        // if two words have same # of repeats pick the one before it.
        if(wordsAndAmount[word]===mostRepeatLetters){ 
          mostRepeatLetters=mostRepeatLetters;
        }else if(wordsAndAmount[word]<mostRepeatLetters){ 
          mostRepeatLetters=mostRepeatLetters;
        }else if(wordsAndAmount[word]>mostRepeatLetters){
          mostRepeatLetters=word;
        }
      } 

  return mostRepeatLetters;
}

// TESTS
console.log("-----");   
console.log(LetterCountI("Today, is the greatest day ever!"));   
console.log(LetterCountI("Hello apple pie"));    
console.log(LetterCountI("No words"));    

非常感谢任何指导。谢谢你!! ^____^

最佳答案

这是工作代码片段:

/*
Using the JavaScript language, have the function LetterCountI(str) take the str 
parameter being passed and return the first word with the greatest number of 
repeated letters. For example: "Today, is the greatest day ever!" should return 
greatest because it has 2 e's (and 2 t's) and it comes before ever which also 
has 2 e's. If there are no words with repeating letters return -1. Words will 
be separated by spaces. 

console.log(LetterCountI("Today, is the greatest day ever!") === "greatest");
console.log(LetterCountI("Hello apple pie") === "Hello");
console.log(LetterCountI("No words") === -1);

Tips: 
This is an interesting problem. What we can do is turn the string to lower case using String.toLowerCase, and then split on "", so we get an array of characters.

We will then sort it with Array.sort. After it has been sorted, we will join it using Array.join. We can then make use of the regex /(.)\1+/g which essentially means match a letter and subsequent letters if it's the same.

When we use String.match with the stated regex, we will get an Array, whose length is the answer. Also used some try...catch to return 0 in case match returns null and results in TypeError.

/(.)\1+/g with the match method will return a value of letters that appear one after the other. Without sort(), this wouldn't work.
*/

function LetterCountI(str){
  var wordsAndAmount={};
	var mostRepeatLetters="";
  var words=str.split(" ");
  
  words.forEach(function(word){
    
      var howManyRepeat=word.toLowerCase().split("").sort().join("").match(/(.)\1+/g);
      
			if(howManyRepeat !== null && howManyRepeat !== 0){ // if there are repeats(at least one value)..
    	 	 	 wordsAndAmount[word] = howManyRepeat;
			  } else{
           wordsAndAmount[word] = -1; // if no words have repeats will return -1 after for in loop.
        }
  });
  
//  console.log(wordsAndAmount);
	for(var word in wordsAndAmount){ // word is the key, wordsAndAmount[word] is the value of word.
   // console.log("Key = " + word);
   // console.log("val = " + wordsAndAmount[word]);
    	if(wordsAndAmount[word].length>mostRepeatLetters.length){ //if two words have same # of repeats pick the one before it.
        mostRepeatLetters=word; 
  		}
  }	
  return mostRepeatLetters ? mostRepeatLetters :  -1;
}

// TESTS
console.log("-----");
console.log(LetterCountI("Today, is the greatest day ever!"));
console.log(LetterCountI("Hello apple pie"));
console.log(LetterCountI("No words"));

/*
split into words

var wordsAndAmount={};
var mostRepeatLetters=0;
  
  
loop through words
	Check if words has repeated letters, if so
  	Push amount into object
    Like wordsAndAmount[word[i]]= a number
  If no repeated letters...no else.
  
Loop through objects
  Compare new words amount of repeated letters with mostRepeatLetters replacing whoever has more.
  In the end return the result of the word having most repeated letters
  If all words have no repeated letters return -1, ie. 
*/

所做的更改:

  • [.] 变成 .,因为 [.] 匹配文字句点符号,不是任何字符,而是换行符
  • 在代码末尾添加了结束 */(最后一个注释 block 未关闭,导致 UNEXPECTED TOKEN ILLEGAL)
  • if(howManyRepeat !== null || howManyRepeat !== 0) 应替换为 if(howManyRepeat !== null && howManyRepeat !== 0)否则 null 会测试与 0 是否相等,并导致 TypeError: Cannot read property 'length' of null" 问题。请注意 .match(/(.)\1+/g).length不能使用,因为匹配结果可能为空,这也会导致出现TypeError。
  • 获取重复次数最多的第一个条目的算法是错误的,因为第一个 if block 允许将后续条目输出为正确的结果(不是第一个,而是最后一个条目)实际上输出了相同的重复)
  • 如果 mostRepeatLetters 为空,则可以返回
  • -1

关于javascript - Coderbyte 上的字母计数 I JavaScript 挑战,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34130331/

相关文章:

javascript - 有没有办法将文件/常量导入到 json 文件中

javascript - 如何使用通过 jQuery 获得的变量?

javascript - 在MVC中获取从View到Controller的数组属性?

长序列上的 C++ 正则表达式段错误

regex - 希望正则表达式可以做到这一点。修复损坏的 XML

JavaScript Chrome 扩展 : Function is not defined

JavaScript - 将多维数组的键从字符串更改为整数

javascript - 用于删除行尾空格模式的正则表达式

python - 在 python 函数中,我是否需要预先分配一个在 if 下有条件出现的值?

javascript - 带有可切换行的 jQuery 表格