ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลข ฟังก์ชันควรคืนค่าอาร์เรย์ของสตริงที่มีตัวเลขถูกตัดทีละหลัก
ตัวอย่าง
โค้ดตัวอย่างด้านล่าง:
const num = 246;
const cutOffEach = (num = 1) => {
const str = String(num);
const res = [];
let temp = '';
for (let i = 0; i < str.length; i++) {
const el = str[i];
temp += el;
res.push(temp);
}
return res;
};
console.log(cutOffEach(num));
ผลลัพธ์
[ '2', '24', '246' ]
คำอธิบายเพิ่มเติม
สร้าง prefix ของสตริงตัวเลข: 2, 24, 246 สามารถเขียนสั้นได้ด้วย `Array.from(str, (_, i) => str.slice(0, i+1))`