我想将一个数字拆分成数字(例如4563到4,5,6,3),然后使这个数字成瘾。 (例如:4 + 5 + 6 + 3 = 18)如何在Javascript中将数字拆分为数字?
我可以编写代码为3位数字或2位数字和......数字分开,但我不能为每个数字编写全局代码。
,所以这是我的2位数字代码:
var a = 23
var b = Math.floor(a/10); // 2
var c = a-b*10; // 3
var total = b+c; // 2+3
console.log(total); // 5
,这是我的3位数字代码:
var a = 456
var b = Math.floor(a/100); // 4
var c = a-b*100; // 56
var d = Math.floor(c/10); // 5
var e = c-d*10; // 6
var total = b+d+e; // 4+5+6
console.log(total); // 15
,但我不能写代码,每个编号的工作。我怎样才能为每个数字编写全局代码?
http://stackoverflow.com/questions/9138064/sum-of-the-digits-of- a-number-javascript – BeNdErR
我猜是http://stackoverflow.com/a/7784630/3894168是你想要的。 – Zee