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

如何获取JSON文件的所有索引以实现随机背景图片功能

实现方案

1. 获取外层商品分类的所有索引

你给出的数据集是对象结构,外层的键就是商品分类的索引,可以直接用Object.keys()获取:

// 获取字符串格式的外层索引,返回结果为 ["1", "2", "3"]
const allCategoryIndexes = Object.keys(data)
// 如果需要使用数字格式的索引,可通过map转换
const allCategoryNumberIndexes = Object.keys(data).map(Number)

2. 获取指定分类下的图片索引

以选中汉堡(Burger)为例,先匹配到对应的分类条目,再提取该分类下图片数组的所有索引:

const selectedProductName = "Burger"
// 匹配对应商品的分类数据
const targetCategory = Object.values(data).find(item => item.name === selectedProductName)
if (targetCategory) {
  // 获取该分类下所有图片的索引,汉堡的返回结果为 [0, 1]
  const pictureIndexes = Array.from({length: targetCategory.picture.length}, (_, idx) => idx)
}
  • 如果你页面的选择器绑定的是商品ID(比如汉堡对应ID 1),可以直接通过data[selectedId]获取对应分类数据,无需遍历查找,性能更高。

3. 随机背景图实现逻辑

拿到索引后可以直接生成随机下标,无需预先存储索引数组即可实现随机取图,完整代码如下:

// 入参为选中的商品名称,返回随机图片链接
function getRandomBgImg(selectedName) {
  const product = Object.values(data).find(item => item.name === selectedName)
  // 无匹配商品或无图片时返回空
  if (!product || !product.picture?.length) return ''
  // 生成随机索引
  const randomIdx = Math.floor(Math.random() * product.picture.length)
  return product.picture[randomIdx].file
}

// 调用示例:选中汉堡时获取随机图
const randomBurgerImg = getRandomBgImg('Burger')
// 赋值给元素背景即可,示例:
// document.querySelector('.your-element').style.backgroundImage = `url(${randomBurgerImg})`

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 15:21:00