สมมติว่าเราได้รับตัวเลข 124 และจำเป็นต้องเขียนฟังก์ชันที่ใช้ตัวเลขนี้เป็นอินพุตและส่งกลับรูปแบบที่ขยายออกมาเป็นสตริง
รูปแบบขยายของ 124 คือ −
'100+20+4'
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const num = 125;
const expandedForm = num => {
const numStr = String(num);
let res = '';
for(let i = 0; i < numStr.length; i++){
const placeValue = +(numStr[i]) * Math.pow(10, (numStr.length - 1 - i));
if(numStr.length - i > 1){
res += `${placeValue}+`
}else{
res += placeValue;
};
};
return res;
};
console.log(expandedForm(num)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ในคอนโซล -
100+20+5