简体   繁体   中英

Function takes a string and returns an object of the letters and number of occurrences -javascript - Homework Warning

Im working with this challenge question and I am struggling with the number count. I can get it work to return the position in the string, but not the actual letter count. Any help is appreciated.

Question -

Write a function named letterCount that takes a string and returns an object with the letters and the number of their occurrences.

My Code so far -

var stringCount = "Hello";

function letterCount(string) {
   var stringObject = {};
   for (var i = 0; i < string.length; i++) {
     stringObject[string[i]] = [i];
   }

   return stringObject;
}

letterCount(stringCount);

You have done almost everything right, only problem is the assignment part, which you need to do this way:

 var stringCount = "Hello"; function letterCount(string) { var stringObject = {}; for (var i = 0; i < string.length; i++) { stringObject[string[i]] = ((stringObject[string[i]]) ? stringObject[string[i]] : 0) + 1; } return stringObject; } console.log(letterCount(stringCount)); 

So technically, what happens in the line:

stringObject[string[i]] = ((stringObject[string[i]]) ? stringObject[string[i]] : 0) + 1;
  • The program checks if that particular index exists in the object.
  • If it doesn't exists (not defined, undefined ), it assigns 0 .
  • If it exists, it takes the same value.
  • It adds 1 to the above value.

The same above line can be written this way:

// Check if the current key exists.
if (typeof stringObject[string[i]] == "undefined") {
  // If it doesn't, initialise it 1.
  stringObject[string[i]] = 1;
} else {
  // If it exists, increment it.
  stringObject[string[i]] = stringObject[string[i]] + 1;
  // Another way:
  // stringObject[string[i]]++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM