從兩端配對 JavaScript 中的陣列
我們需要編寫一個 JavaScript 函式,該函式接收一個數字/字串文字陣列,並返回另一個數組的陣列。每個子陣列正好包含兩個元素,第 n 個元素從起始第 n 個元素開始到末尾第 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
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP