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

วิธีหาค่าสูงสุดและต่ำสุดในอาร์เรย์ JavaScript

ใช้ Math.max() และ Math.min() ร่วมกับ apply() หรือ Spread Syntax (...) เพื่อหาค่าสูงสุดและต่ำสุดในอาร์เรย์

ตัวอย่าง

<html>
  <body>
    <script>
      var arr = [50, 30, 70, 60];

      // ใช้ apply (รองรับเบราว์เซอร์เก่า)
      document.write("Maximum Value: " + Math.max.apply(null, arr));
      document.write("<br>Minimum Value: " + Math.min.apply(null, arr));

      // ใช้ Spread Syntax (ES6 - แนะนำ)
      // document.write("Max: " + Math.max(...arr));
      // document.write("Min: " + Math.min(...arr));
    </script>
  </body>
</html>

ผลลัพธ์

Maximum Value: 70
Minimum Value: 30

ข้อควรระวัง

  • Math.max() และ Math.min() รับพารามิเตอร์ทีละตัว ไม่ใช่อาร์เรย์ → ต้องใช้ apply หรือ ...
  • อาร์เรย์ว่าง: Math.max(...[]) = -Infinity, Math.min(...[]) = Infinity
  • มีค่าไม่ใช่ตัวเลข: ผลลัพธ์จะเป็น NaN
  • ขีดจำกัดจำนวนอาร์กิวเมนต์ (call stack limit) ประมาณหลายหมื่นรายการ → อาร์เรย์ใหญ่ๆ ควรใช้ลูปหรือ reduce

วิธีใช้ reduce (สำหรับอาร์เรย์ใหญ่)

const max = arr.reduce((a, b) => Math.max(a, b), -Infinity);
const min = arr.reduce((a, b) => Math.min(a, b), Infinity);