ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน 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