[英]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. 我想使用toString
和Number
方法添加num
变量的总和。 I first turn num
into the string num = '12345'
. 我首先将num
转换为字符串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. 您没有将num.toString()
的结果分配给任何东西。
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. 您可以使用split,map和reduce拆分数组,将其映射为整数,然后使用reduce函数对整数求和。
You could eliminate the map if you want to move parse into the reduce, but I like to keep the steps separate. 如果您想将解析移入reduce中,则可以消除该映射,但是我想将步骤分开。
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 :) 如果您将来有任何问题,请先搜索一下,然后在这里写:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.