我想將一個數字拆分成數字(例如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