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

ขยายตัวเลขเป็น Place Values (Expanded Form) - JavaScript

แยกตัวเลขเป็น Place Values (ค่าตำแหน่ง) เช่น 123 → [100, 20, 3]

ตัวอย่างโค้ด (Recursive)

const placeValue = (num, res = [], factor = 1) => {
  if (num) {
    const val = (num % 10) * factor;
    res.unshift(val);
    return placeValue(Math.floor(num / 10), res, factor * 10);
  }
  return res;
};

console.log(placeValue(123));

ผลลัพธ์

[ 100, 20, 3 ]

วิธีแบบ String (เข้าใจง่ายกว่า)

const placeValue = num => 
  String(num).split('').map((digit, i, arr) => 
    +digit * 10 ** (arr.length - 1 - i)
  ).filter(v => v !== 0); // ไม่รวม 0

console.log(placeValue(123));    // [100, 20, 3]
console.log(placeValue(1002));   // [1000, 2]

รวม 0 ด้วย

const placeValueWithZeros = num => 
  String(num).split('').map((digit, i, arr) => 
    +digit * 10 ** (arr.length - 1 - i)
  );

console.log(placeValueWithZeros(1002)); // [1000, 0, 0, 2]