เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้จำนวนเต็มบวกเป็นอาร์กิวเมนต์เดียว ฟังก์ชันควรสร้างและส่งกลับอาร์เรย์ของตัวเลขทั้งหมดที่แบ่งจำนวนอินพุตอย่างแม่นยำ
ตัวอย่างเช่น −
หากตัวเลขที่ป้อนคือ −
const num = 12;
จากนั้นผลลัพธ์ควรเป็น −
const output = [1, 2, 3, 4, 6, 12];
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const findFactors = (num = 1) => {
let half = Math.floor(num / 2);
const res = [1]; // 1 will be a part of every solution.
let i, j;
num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);
for (i; i <= half; i += j) {
if(num % i === 0){
res.push(i);
};
};
res.push(num);
return res;
};
console.log(findFactors(12)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์บนคอนโซล -
[ 1, 2, 3, 4, 6, 12 ]