在 JavaScript 中返回展開形式的數字
問題
我們需要編寫一個 JavaScript 函式,該函式接受一個數字並返回一個展開形式的數字字串,其中指示每個數字的位值。
示例
以下是程式碼 −
const num = 56577; const expandedForm = (num = 0) => { const str = String(num); let res = ''; let multiplier = Math.pow(10, str.length - 1); for(let i = 0; i < str.length; i++){ const el = +str[i]; const next = +str[i + 1]; if(el){ res += (el * multiplier); }; if(next){ res += ' + '; }; multiplier /= 10; }; return res; }; console.log(expandedForm(num));
輸出
以下是控制檯輸出 −
50000 + 6000 + 500 + 70 + 7
廣告