Home > database >  Why is the Number() function not working when I use it this way?
Why is the Number() function not working when I use it this way?

Time:01-28

function sumDigits(num) {
  // your code here
  let nums = num.toString();
  let sum = 0;
  
  for(let i = 0;i<nums.length;i  ){
       Number(nums[i]);
      console.log(typeof nums[i]);
      sum  = nums[i];
  }

  return sum;
}


var output = sumDigits(1148);
console.log(output); // --> 14

Can someone explain why Number(nums[i]) does not change the type of the variable. Or any other way to solve this problem? The function is supposed to take in an integer value and add all the digits and return an integer.

When I tried to run the code i couldn't get the string to convert back into a number and would just add the value of sums to the front of the string.

CodePudding user response:

You are not saving the value returned by Number(nums[i]). But since here you are not using it more than once, you can just add it to the sum without assigning it to a variable.

function sumDigits(num) {
  // your code here
  let nums = num.toString();
  let sum = 0;

  for (let i = 0; i < nums.length; i  ) {
    sum  = Number(nums[i]);
  }

  return sum;
}

var output = sumDigits(1148);
console.log(output); // --> 14

CodePudding user response:

Number does not change the value it's used on. (It couldn't when used on a string, anyway, since strings in JavaScript are immutable.) It just returns a number. So you have to use that return value.

Try this instead:

for(let i = 0; i < nums.length; i  ){
    sum  = Number(nums[i]);
}
  • Related