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

การกลับเครื่องหมายจำนวนเต็มในอาร์เรย์ใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของจำนวนเต็ม (ลบและบวก) ฟังก์ชันควรแปลงบวกเป็นลบ และลบเป็นบวก และคืนค่าอาร์เรย์ที่ได้

ตัวอย่าง

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

const arr = [5, 67, -4, 3, -45, -23, 67, 0];
const invertSigns = (arr = []) => {
  const res = [];
  for(let i = 0; i < arr.length; i++){
    const el = arr[i];
    if(+el && el !== 0){
      const inverted = el * -1;
      res.push(inverted);
    }else{
      res.push(el);
    };
  };
  return res;
};
console.log(invertSigns(arr));

ผลลัพธ์

[ -5, -67, 4, -3, 45, 23, -67, 0 ]