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

คำนวณผลรวมตัวเลขระหว่างค่าสูงสุดและต่ำสุดของอาร์เรย์ใน JavaScript

เราต้องเขียนฟังก์ชัน sumBetween() รับอาร์เรย์ [a,b] สองสมาชิก คืนผลรวมตัวเลขระหว่าง a และ b รวม a และ b ด้วย

เช่น

[4, 7] = 4+5+6+7 = 22
[10, 6] = 10+9+8+7+6 = 40

เขียนโค้ด

ตัวอย่าง

const arr = [10, 60];
const sumUpto = (n) => (n*(n+1))/2;
const sumBetween = (array) => {
  if(array.length !== 2){
    return -1;
  }
  const [a, b] = array;
  return sumUpto(Math.max(a, b)) - sumUpto(Math.min(a, b)) + Math.min(a,b);
};
console.log(sumBetween(arr));
console.log(sumBetween([4, 9]));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็น

1785
39