Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a function addThreeNumsFromString that takes a single string
- * as argument. The given string will consist of three numbers
- * separated by a space. The function will add the three the numbers
- * and return their sum.
- */
- /* This is the high-level view of what's going wrong with this
- * program.
- */
- console.log(addThreeNumsFromString("5 5 5"))
- // will log 15
- console.log(addThreeNumsFromString("4 2 1"))
- // will log 7
- //Your Answer:
- var sum = 0;
- // For my explanations of this function, just assume that the argument
- // is the string "5 5 5".
- function addThreeNumsFromString (str){
- /* What did you want to do here?
- * - What you wanted to do:
- * Split the string into just the numbers, and ignore everything
- * else. Correct statement is:
- * var newArr = str.split(" ")
- * - What you did:
- * Split the string into individual characters:
- */
- var newArr = str.split("");
- */
- /* What did you want to do in this loop?
- * - You wanted to loop through the numbers in the string.
- * for (var i = 0; i < newArr.length; i++) {
- * - What you actually did: loop through the *whole string* (all the
- * characters in the string).
- */
- for (var i = 0; i < str.length; i++) {
- /* - What you wanted to say here:
- * Take the ith number in the string and add that to sum.
- * Correct statement:
- * sum += Number(newArr[i])
- * - What you actually did: take the ith *string* in newArr and
- * add that to sum.
- * - What you actually wanted to do is further complicated by
- * trouble with scope here. Where does `sum` actually live? It's
- * not defined in `addThreeNumsFromString`, it's defined in the
- * enclosing scope, when you said `var sum = 0`. Handuful of
- * wrong details here, but I'll cover those in a more detailed
- * breakdown, later.
- */
- sum += newArr[i]
- }
- /* Returning your sum is the right thing to do, but is also
- * complicated by troubles with scope. You can see this by running
- * this function more than once and observing the return value.
- */
- return sum;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement