เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลข ฟังก์ชันควรคืนค่าองค์ประกอบตรงกลางของอาร์เรย์
ตัวอย่างเช่น:
ถ้าอาร์เรย์คือ:
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 ]