Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

คืนค่ารูปแบบขยายของตัวเลขใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลขและคืนสตริงของรูปแบบขยาย (expanded form) ของตัวเลข แสดงค่าทศนิยมของแต่ละหลัก

ตัวอย่าง

โค้ดด้านล่างนี้

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