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

วิธีหาตัวเลขมากที่สุดในอาร์เรย์ที่มีองค์ประกอบ undefined - JavaScript

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ที่มีตัวเลขบางตัว สตริงบางส่วน และค่า falsy บางส่วน

ฟังก์ชันของเราควรคืนค่าตัวเลขที่มากที่สุดจากอาร์เรย์

ตัวอย่างเช่น:

ถ้าอาร์เรย์อินพุตเป็นดังต่อไปนี้พร้อมค่า undefined บางส่วน:

const arr = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];

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

ตัวอย่าง

const arr = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];
const pickBiggest = arr => {
  let max = -Infinity;
  for (let i = 0; i < arr.length; i++) {
    if (!+arr[i]) {
      continue;
    }
    max = Math.max(max, +arr[i]);
  }
  return max;
};
console.log(pickBiggest(arr));

ผลลัพธ์

โค้ดนี้จะแสดงผลลัพธ์ดังต่อไปนี้บนคอนโซล:

65