Created
May 26, 2020 02:46
-
-
Save imbyc/31af4c0f30884bd2cef304cc2f14c5e2 to your computer and use it in GitHub Desktop.
[js 将一维数组按指定长度转为二维数组] https://xugaoyi.com/pages/f1acb712033ac8da/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function pages(arr, len) { | |
const pages = [] | |
arr.forEach((item, index) => { | |
const page = Math.floor(index / len) | |
if (!pages[page]) { | |
pages[page] = [] | |
} | |
pages[page].push(item) | |
}) | |
return pages | |
} | |
// 使用 | |
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] | |
console.log(pages(arr, 3)) // [[1, 2, 3], [4, 5, 6], [7, 8, 9]] | |
console.log(pages(arr, 8)) // [[1, 2, 3, 4, 5, 6, 7, 8], [9]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment