78 lines
1.9 KiB
Markdown
78 lines
1.9 KiB
Markdown
---
|
||
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转为二维数组,再分页渲染到页面。
|
||
|
||

|
||
|
||
```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>
|
||
```
|