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