数组中的开始和结束对-JavaScript
我们需要编写一个JavaScript函数,该函数接受Number/String文字数组,并返回另一个数组数组。每个子数组正好包含两个元素,第n个元素从最后一个开始。
例如-
如果数组是-
const arr = [1, 2, 3, 4, 5, 6];
那么输出应该是-
const output = [[1, 6], [2, 5], [3, 4]];
示例
以下是代码-
const arr = [1, 2, 3, 4, 5, 6];
const edgePairs = arr => {
const res = [];
const upto = arr.length % 2 === 0 ? arr.length / 2 : arr.length / 2 - 1;
for(let i = 0; i < upto; i++){
res.push([arr[i], arr[arr.length-1-i]]);
};
if(arr.length % 2 !== 0){
res.push([arr[Math.floor(arr.length / 2)]]);
};
return res;
};
console.log(edgePairs(arr));输出结果
以下是控制台中的输出-
[ [ 1, 6 ], [ 2, 5 ], [ 3, 4 ] ]
热门推荐
10 大雪生日祝福语大全简短
11 朋友花篮开业祝福语简短
12 宝子生日祝福语简短
13 祖国生日祝福语简短英文
14 姥爷生日诗句祝福语简短
15 拜年啦祝福语大全简短
16 老爸生日暴富祝福语简短
17 端午老师祝福语简短优美
18 十月简短祝福语