ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้อาร์เรย์ผสมของการแสดงตัวเลขและสตริงของจำนวนเต็ม
ฟังก์ชันของเราควรบวกจำนวนเต็มสตริงและลบออกจากจำนวนเต็มที่ไม่ใช่สตริง
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [5, 2, '4', '7', '4', 2, 7, 9];
const integerDifference = (arr = []) => {
let res = 0;
for(let i = 0; i < arr.length; i++){
const el = arr[i];
if(typeof el === 'number'){
res += el;
}else if(typeof el === 'string' && +el){
res -= (+el);
};
};
return res;
};
console.log(integerDifference(arr)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
10