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

การหาองค์ประกอบกลางของอาร์เรย์ใน JavaScript

คำอธิบาย

เขียนฟังก์ชันคืนค่าองค์ประกอบกลางของอาร์เรย์ ถ้าจำนวนคู่ให้คืน 2 ตัวกลาง

ตัวอย่าง

[1,2,3,4,5,6,7] → [4] | [1,2,3,4,5,6] → [3,4]

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

const arr = [1, 2, 3, 4, 5, 6, 7];

const middle = function() {
  const half = this.length >> 1;
  const offset = 1 - this.length % 2;
  return this.slice(half - offset, half + 1);
};

Array.prototype.middle = middle;
console.log(arr.middle());
console.log([1, 2, 3, 4, 5, 6].middle());

ผลลัพธ์

[ 4 ] [ 3, 4 ]