เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้อาร์เรย์ของ Numbers ฟังก์ชั่นควรส่งคืนองค์ประกอบที่อยู่ตรงกลางสุดของอาร์เรย์
ตัวอย่างเช่น หากอาร์เรย์เป็น −
const arr = [1, 2, 3, 4, 5, 6, 7];
จากนั้นผลลัพธ์ควรเป็น 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 ]