vuepress-theme-vdoing/docs/01.前端/25.JavaScript文章/70.将一维数组按指定长度转为二维数组.md

78 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 将一维数组按指定长度转为二维数组
date: 2020-02-23 13:49:31
permalink: /pages/f1acb712033ac8da
categories:
- 前端
- JavaScript文章
tags:
- null
author:
name: xugaoyi
link: https://github.com/xugaoyi
---
# 将一维数组按指定长度转为二维数组
将一维数组按指定长度转为二维数组
```js
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]]
```
## 应用场景示例
如图按需求图标模块中的图标个数是不确定的每页最多显示8个超出8个的显示到第二页实现向左滑动翻页。提供的数据是一个一维数组这时就可以使用上面的代码按长度为8转为二维数组再分页渲染到页面。
![](https://cdn.staticaly.com/gh/xugaoyi/image_store/blog/20200223142410.jpg)
```html
<template>
<swiper>
<swiper-slide v-for="(page, index) of pages" :key="index">
<div class="icon" v-for="item of page" :key="item.id">
<div class="icon-img">
<img :src="item.imgUrl">
</div>
<p>{{item.desc}}</p>
</div>
</swiper-slide>
</swiper>
<template>
<script>
...
data () {
return {
iconList: [] // 图标数据
}
},
computed: {
pages () {
const pages = []
this.iconList.forEach((item, index) => {
const page = Math.floor(index / 8)
if (!pages[page]) {
pages[page] = []
}
pages[page].push(item)
})
return pages
}
}
</script>
```