在 JavaScript 中从两端配对数组

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/31 18:52:17

我们需要编写一个 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 ] ]

相关文章


有用资源