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

หาค่ามากที่สุดจากหลายตัวเลข - JavaScript

หาค่าสูงสุดจากตัวเลขหลายตัว ใช้ Rest Parameters (...nums) รับจำนวนอาร์กิวเมนต์ไม่จำกัด

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

const findGreatest = (...nums) => {
  let max = -Infinity;
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] > max) max = nums[i];
  }
  return max;
};

console.log(findGreatest(5, 6, 3, 5, 7, 5));

ผลลัพธ์

7

วิธีแบบ Built-in (แนะนำ)

const findGreatest = (...nums) => Math.max(...nums);

// หรือถ้ามีอาร์เรย์อยู่แล้ว
const arr = [5, 6, 3, 5, 7, 5];
console.log(Math.max(...arr));

Math.max() รองรับหลายอาร์กิวเมนต์ แตต้องใช้ Spread operator กับอาร์เรย์