เราต้องเขียนฟังก์ชันที่รับตัวเลขและแยกเลขหลักแต่ละหลักเป็นอาร์เรย์ โดยห้ามแปลงเป็นสตริงหรือใช้ฟังก์ชัน ES6
ตัวอย่าง: 55678 → [5,5,6,7,8]
ตัวอย่างโค้ด
const num = 55678;
const numberToArray = (num) => {
const res = [];
while (num) {
const last = num % 10;
res.unshift(last);
num = Math.floor(num / 10);
}
return res;
};
console.log(numberToArray(num));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
[ 5, 5, 6, 7, 8 ]