简体   繁体   中英

Sum of Digits using tostring and number methods javascript

Can someone explain what I am doing wrong in this problem? I want to add the sum of the num variable using toString and Number methods. I first turn num into the string num = '12345' . Then I loop through string, turn it into a number and add it to the sum.

var num = 12345;

function sumDigits(num) {     
  var sumOfDigits = 0;     
  num.toString();     
  for(var i = 0; i < num.length; i++){    
    sumOfDigits += Number(num[i]);     
  }     
  return sumOfDigits;    
}

You're not assigning the result of num.toString() to anything.

 var num = 12345; function sumDigits(num) { var sumOfDigits = 0; num = num.toString(); for (var i = 0; i < num.length; i++) { sumOfDigits += Number(num[i]); } return sumOfDigits; } console.log(sumDigits(num)); 

Updated:

You can use split, map and reduce to split the array, map it to integers, then use a reduce function to sum the integers.

You could eliminate the map if you want to move parse into the reduce, but I like to keep the steps separate.

 var num = 12345; function sumDigits(num) { var sumOfDigits = num .toString() .split('') .map(function(n) { return parseInt(n);}) .reduce(function(acc, val) { return acc + val; }, 0 ); return sumOfDigits; } var sum = sumDigits(num); console.log(sum) 

I believe you can use this one :

    var num = 12345;
    function sumDigits(num) {
    //empty variable
    var str;
    //check type of the incoming value
    (typeof num == "string") ? str = num : str = num.toString();
    //this is the same with above if you don't know how to use short handed if else 
    /*
        if(typeof num == "string"){
            str = num;
        } else {
            str = num.toString();
        }
    */
    //Array's split Method and a variable which u have create already
    var arr = str.split(''), sumOfDigits = 0;
    for(var i in arr){
        //You should use parseInt() method.
        sumOfDigits += parseInt(arr[i]);
    }
    //return the sum of the digits
    return sumOfDigits;
};
console.log(sumDigits(num));

If you have future problems please first search a bit then write here :)

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