如何选择一个数组的中间?-JavaScript
我们需要编写一个包含数字数组的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 ]
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短