You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS实现数组元素按规则交错排布到top、bottom div的方法

数组元素交错排布渲染实现方案

核心思路

要满足排布要求,核心要解决两个问题:一是最大程度减少相同key的元素相邻,二是自动适配任意长度数组,自动拆分元素到两个容器,核心处理逻辑如下:

  • 先把原数组元素按key值拆成两个独立队列,方便按规则取用
  • 排列时优先选择和上一个元素key不同的队列取数,如果目标队列已空,再从剩余队列取数,从根源减少同key相邻的可能
  • 首次排列优先从元素量更多的队列开始取,避免某类元素剩余太多导致后期大量相邻
  • 每次取数时从对应队列随机抽取元素,保证排布有随机性,不会生成固定顺序
  • 排列完成后自动按总长度平分数组,前半段渲染到.top容器,后半段渲染到.bottom容器,不需要硬编码每段固定长度

完整代码

JS逻辑

const myArray = [
  { 1: 'test_12' },
  { 2: 'test_13' },
  { 2: 'test_14' },
  { 1: 'test_15' },
  { 2: 'test_16' },
  { 2: 'test_17' },
  { 2: 'test_18' },
  { 1: 'test_19' },
  { 1: 'test_20' },
  { 2: 'test_21' }
]

// 按key分组存储
const groupQueue = {
  1: [],
  2: []
}
myArray.forEach(item => {
  const itemKey = Object.keys(item)[0]
  groupQueue[itemKey].push(item)
})

const sortedResult = []
let lastPickedKey = null

// 交错生成排布序列
while (groupQueue[1].length > 0 || groupQueue[2].length > 0) {
  let currentPickKey
  if (lastPickedKey === null) {
    // 首次取数优先选元素更多的分组
    currentPickKey = groupQueue[1].length >= groupQueue[2].length ? '1' : '2'
  } else {
    // 优先取和上一个key不同的分组元素
    const targetKey = lastPickedKey === '1' ? '2' : '1'
    currentPickKey = groupQueue[targetKey].length > 0 
      ? targetKey 
      : (groupQueue[1].length > 0 ? '1' : '2')
  }

  // 从目标分组随机取一个元素
  const randomIndex = Math.floor(Math.random() * groupQueue[currentPickKey].length)
  const pickedItem = groupQueue[currentPickKey].splice(randomIndex, 1)[0]
  sortedResult.push(pickedItem)
  lastPickedKey = currentPickKey
}

// 自动平分元素到两个容器,适配任意长度
const splitPoint = Math.ceil(sortedResult.length / 2)
const topItems = sortedResult.slice(0, splitPoint)
const bottomItems = sortedResult.slice(splitPoint)

// 渲染内容,先清空容器再追加,避免内容覆盖
$('.top').empty()
topItems.forEach(item => {
  const key = Object.keys(item)[0]
  $('.top').append(`<p>${item[key]}</p>`)
})

$('.bottom').empty()
bottomItems.forEach(item => {
  const key = Object.keys(item)[0]
  $('.bottom').append(`<p>${item[key]}</p>`)
})

样式代码

.top {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
  width: 100%;
  height: 3em;
  background-color: pink;
}

.bottom {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
  width: 100%;
  height: 3em;
  background-color: gold;
}

页面结构

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="top"></div>
<div class="bottom"></div>

方案特性

  • 适配任意长度数组:自动计算拆分点,不管数组总长度是奇数还是偶数都能正常拆分,不需要硬编码固定元素数量
  • 同key相邻概率最低:只有当另一类元素全部用完时才会出现同key相邻的情况,最大程度满足排布要求
  • 结果有随机性:每次从目标分组随机取数,不会生成固定的排列结果
  • 修复原草稿问题:解决了原代码循环内重复渲染覆盖内容、元素重复取用、硬编码长度不通用的问题

内容的提问来源于stack exchange,提问作者seriously

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 04:54:28