如何在 JavaScript 中將數組拆分為偶數塊
簡介
數組是 JavaScript 編程中最常用的結構之一,這就是為什麼了解其內置方法很重要的原因。
在本教程中,我們將了解如何將數組拆分為 n
塊 JavaScript 中的大小 .
具體來說,我們來看看兩種方法:
- 使用
slice()
方法和for
循環 - 使用
splice()
方法和一個while
循環
使用 slice() 將數組分割成偶數塊 方法
slice()
方法:
注意: start
和 end
可以是負整數,這只是表示它們是從數組末尾枚舉的。 -1
作為數組的最後一個元素,-2
倒數第二個等等……
slice()
返回的數組 返回一個淺拷貝,這意味著原始數組中的任何引用都將按原樣複製,並且不會為全新的對象分配內存。
因此,要將列表或數組切成偶數塊,讓我們使用 slice()
方法:
function sliceIntoChunks(arr, chunkSize) {
const res = [];
for (let i = 0; i < arr.length; i += chunkSize) {
const chunk = arr.slice(i, i + chunkSize);
res.push(chunk);
}
return res;
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(sliceIntoChunks(arr, 3));
運行上面的代碼會產生以下輸出:
[[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ]]
在上面的代碼中,我們分解了 arr
分成大小為 3
的小塊 , 通過遍歷數組並每隔 chunkSize
對其進行切片 .在最後一次迭代中,將只有一個元素 (10
) 離開,它必須組成自己的塊。
使用 splice() 將數組分割成偶數塊 方法
即使 splice()
方法可能看起來類似於 slice()
方法,它的用途和副作用是非常不同的。讓我們仔細看看:
// Splice does the following two things:
// 1. Removes deleteCount elements starting from startIdx (in-place)
// 2. Inserts the provided new elements (newElem1, newElem2...) into myArray starting with index startIdx (also in-place)
// The return value of this method is an array that contains all the deleted elements
myArray.splice(startIdx, deleteCount, newElem1, newElem2...)
let arrTest = [2, 3, 1, 4]
let chunk = arrTest.splice(0,2)
console.log(chunk) // [2, 3]
console.log(arrTest) // [1, 4]
讓我們通過一個代碼示例來看看這一點:
免費電子書:Git Essentials
查看我們的 Git 學習實踐指南,其中包含最佳實踐、行業認可的標準以及隨附的備忘單。停止谷歌搜索 Git 命令並真正學習 它!
function spliceIntoChunks(arr, chunkSize) {
const res = [];
while (arr.length > 0) {
const chunk = arr.splice(0, chunkSize);
res.push(chunk);
}
return res;
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(spliceIntoChunks(arr, 2));
運行此代碼產生:
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ] ]
這裡我們使用 while
循環遍歷數組。在每次迭代中,我們執行拼接操作並將每個塊推送到結果數組中,直到原始數組中沒有更多元素(arr.length > 0
)。
需要注意的一個非常重要的事情是 splice()
更改原始數組。其中 slice()
創建原始數組的副本,因此原始數組不會有任何變化。
結論
在本文中,我們介紹了幾種在 JavaScript 中將列表拆分為偶數塊的簡單方法。在此過程中,我們學習瞭如何使用幾個內置數組方法,例如 slice()
和 splice()
.