Advertisement
beelzebielsk

stringsToNumber-high

Oct 27th, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a function addThreeNumsFromString that takes a single string
  2.  * as argument. The given string will consist of three numbers
  3.  * separated by a space. The function will add the three the numbers
  4.  * and return their sum.
  5.  */
  6.  
  7. /* This is the high-level view of what's going wrong with this
  8.  * program.
  9.  */
  10.  
  11. console.log(addThreeNumsFromString("5 5 5"))
  12. // will log 15
  13. console.log(addThreeNumsFromString("4 2 1"))
  14. // will log 7
  15.  
  16.  
  17. //Your Answer:
  18. var sum = 0;
  19.  
  20. // For my explanations of this function, just assume that the argument
  21. // is the string "5 5 5".
  22. function addThreeNumsFromString (str){
  23.   /* What did you want to do here?
  24.    * - What you wanted to do:
  25.    *   Split the string into just the numbers, and ignore everything
  26.    *   else. Correct statement is:
  27.    *      var newArr = str.split(" ")
  28.    * - What you did:
  29.    *   Split the string into individual characters:
  30.    */
  31.   var newArr = str.split("");
  32.    */
  33.   /* What did you want to do in this loop?
  34.    * - You wanted to loop through the numbers in the string.
  35.    *   for (var i = 0; i < newArr.length; i++) {
  36.    * - What you actually did: loop through the *whole string* (all the
  37.    *   characters in the string).
  38.    */
  39.    for (var i = 0; i < str.length; i++) {
  40.     /* - What you wanted to say here:
  41.      *   Take the ith number in the string and add that to sum.
  42.      *   Correct statement:
  43.      *     sum += Number(newArr[i])
  44.      * - What you actually did: take the ith *string* in newArr and
  45.      *   add that to sum.
  46.      * - What you actually wanted to do is further complicated by
  47.      *   trouble with scope here. Where does `sum` actually live? It's
  48.      *   not defined in `addThreeNumsFromString`, it's defined in the
  49.      *   enclosing scope, when you said `var sum = 0`. Handuful of
  50.      *   wrong details here, but I'll cover those in a more detailed
  51.      *   breakdown, later.
  52.      */
  53.     sum += newArr[i]
  54.   }
  55.   /* Returning your sum is the right thing to do, but is also
  56.    * complicated by troubles with scope. You can see this by running
  57.    * this function more than once and observing the return value.
  58.    */
  59.   return sum;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement