可能在 javascript 中使用回圈而不是方法
這是我的練習規格:
撰寫一個被呼叫的函式Swapper()
,它接受一個陣列的輸入作為引數,并在交換前半部分和后半部分后,將修改后的陣列回傳給呼叫者。例子
input: [5, 11, 1, 44, 2, 43]
output: [44, 2, 43, 5, 11, 1]
如果陣列的長度為奇數,則中心值必須保持不變。
uj5u.com熱心網友回復:
看一下這個
const sample = [5, 11, 1, 44, 2, 43];
var len = sample.length;
if(len%2==0)
var split = len / 2;
else
var split = (len 1)/2;
var arr1 = sample.slice(0,split);
var arr2 = sample.slice(split, len);
[arr1, arr2] = [arr2, arr1]
const arr = [arr1,arr2];
uj5u.com熱心網友回復:
You can use array.splice method to split an array in half and store the result in a temporary variavble and than use spread operator to combine both the arrays into a single one.
let a = [1,2,3,4,5,6];
let temp = a.splice(0,a.length/2);
let splitted = [...a , ...temp];
console.log(splitted)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/388520.html
標籤:javascript 数组 功能 循环
