हमें एक 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 ]