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

การยกกำลังสองทุกหลักของตัวเลขด้วย split() ใน JavaScript

เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลขหนึ่งตัวเป็นอาร์กิวเมนต์เดียว ฟังก์ชันต้องยกกำลังสองทุกหลักของตัวเลข นำมาต่อกัน และสร้างตัวเลขใหม่

ตัวอย่าง

ถ้าตัวเลขนำเข้าคือ:

const num = 12349;

ผลลัพธ์ควรเป็น:

const output = 1491681;

เพราะ '1' + '4' + '9' + '16' + '81' = 1491681

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

const num = 12349;
const squareEvery = (num = 1) => {
  let res = '';
  const numStr = String(num);
  const numArr = numStr.split('');
  numArr.forEach(digit => {
    const square = (+digit) * (+digit);
    res += square;
  });
  return +res;
};
console.log(squareEvery(num));

ผลลัพธ์

1491681