数组中的首尾对 - JavaScript


我们需要编写一个 JavaScript 函数,该函数接受一个数字/字符串字面量的数组,并返回另一个数组数组。每个子数组包含从开始到从结尾数第 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 ] ]

更新日期:18-9-2020

100 次浏览

开启您的 职业生涯

完成课程即可获得认证

开始学习
广告
© . All rights reserved.