从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 送给学长毕业祝福语简短