数组中的首尾对 - 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 ] ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP