求助:从转置后的二维数组按索引随机选元素并生成URL数组
解决方案:按编号位置随机选择生成URL数组
没问题,我来帮你搞定这个需求!转置后的数组是按字母分组的,现在我们需要从每个编号后缀(01到12)对应的所有元素里随机选一个,再生成对应的URL数组。
实现代码
const fileName = [ ["a01", "a02", "a03", "a04", "a05", "a06", "a07", "a08", "a09", "a10", "a11", "a12"], ["b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "b12"], ["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12"], ["d01", "d02", "d03", "d04", "d05", "d06", "d07", "d08", "d09", "d10", "d11", "d12"], ["e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11", "e12"], ["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12"], ["g01", "g02", "g03", "g04", "g05", "g06", "g07", "g08", "g09", "g10", "g11", "g12"], ["h01", "h02", "h03", "h04", "h05", "h06", "h07", "h08", "h09", "h10", "h11", "h12"], ["i01", "i02", "i03", "i04", "i05", "i06", "i07", "i08", "i09", "i10", "i11", "i12"], ["j01", "j02", "j03", "j04", "j05", "j06", "j07", "j08", "j09", "j10", "j11", "j12"], ["k01", "k02", "k03", "k04", "k05", "k06", "k07", "k08", "k09", "k10", "k11", "k12"] ]; function randomiseByNumberSuffix() { // 确定编号位置的总数(这里是12个,对应01到12) const positionCount = fileName[0].length; const randomSelection = []; for (let index = 0; index < positionCount; index++) { // 收集当前编号位置的所有候选元素(比如index=0对应所有x01) const candidates = fileName.map(group => group[index]); // 生成有效随机索引,从候选列表中选一个元素 const randomIndex = Math.floor(Math.random() * candidates.length); const selected = candidates[randomIndex]; // 拼接成目标URL并加入结果数组 randomSelection.push(`assets/music/${selected}.mp3`); } console.log(randomSelection); return randomSelection; } // 调用测试 randomiseByNumberSuffix();
代码关键点解释
- 遍历编号位置:通过
fileName[0].length获取总共有多少个编号位置,循环每个索引对应后缀01到12的位置。 - 收集候选元素:用
map方法把每个字母分组里的对应位置元素提取出来,形成该编号的候选列表。 - 安全随机选择:
Math.floor(Math.random() * candidates.length)保证随机索引不会超出候选列表的长度,避免越界报错。 - URL生成:和你原来的逻辑保持一致,直接拼接字符串生成MP3路径。
简洁版优化(可选)
如果想让代码更紧凑,可以用Array.from替代for循环,一行完成核心逻辑:
function randomiseByNumberSuffix() { const randomSelection = Array.from({ length: fileName[0].length }, (_, index) => { const candidates = fileName.map(g => g[index]); return `assets/music/${candidates[Math.floor(Math.random() * candidates.length)]}.mp3`; }); console.log(randomSelection); return randomSelection; }
内容的提问来源于stack exchange,提问作者Guillermo Brachetta
相关产品推荐
相关产品推荐

