JS打乱blob数组后如何获取原指定blob元素的新索引值
解决方案
方案1:直接匹配目标元素(最简实现,适合绝大多数场景)
你只需要在打乱数组前先记录要跟踪的目标Blob,打乱后重新查找它的索引即可:
const data = { pictures: ['blob1','blob2','blob3'], pictureIndex: 0 } // 1. 先记录原索引对应的目标元素 const target = data.pictures[data.pictureIndex]; // 2. 打乱数组 shuffleArray(data.pictures); // 3. 查找目标元素在新数组中的索引,更新到pictureIndex data.pictureIndex = data.pictures.indexOf(target); console.log(data.pictures, data.pictureIndex) // 可直接验证结果 function shuffleArray(array) { let currentIndex = array.length, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]]; } return array; }
方案2:打乱时同步跟踪索引(适合超大数组/元素存在重复的场景)
如果数组元素量极大,或者存在重复元素,你可以修改打乱方法,直接返回新的目标索引,避免二次遍历数组:
const data = { pictures: ['blob1','blob2','blob3'], pictureIndex: 0 } // 传入原目标索引,打乱后直接返回新的目标索引 data.pictureIndex = shuffleArray(data.pictures, data.pictureIndex); function shuffleArray(array, targetIndex) { let currentIndex = array.length, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; // 交换元素时同步更新目标索引的位置 if (currentIndex === targetIndex) { targetIndex = randomIndex; } else if (randomIndex === targetIndex) { targetIndex = currentIndex; } [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]]; } return targetIndex; }
注意事项
- 如果你的Blob数组存在完全相同的元素,方案1的
indexOf会返回第一个匹配项的位置,这种场景建议使用方案2,或者给每个Blob绑定唯一标识做匹配。
内容的提问来源于stack exchange,提问作者Sara Ree
相关产品推荐
相关产品推荐

