数组中的开始和结束对-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 ] ]