ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน 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 ]