javascript - 随机播放对象数组无法按预期工作
问题描述
随机播放对象数组无法按预期工作
我已经尝试了在这里找到的所有不同类型的随机播放方法。如果我在 js.fiddle 上运行它们,一切正常,但由于我在我的代码中使用它,它不再随机播放。没有错误消息或任何东西。它只是没有做任何事情。我在这里阅读了所有关于洗牌对象的线程,但我没有发现任何可以解决这个问题的东西。
我使用来自https://randomuser.me/的 API来获取随机用户。这些存储在我想要洗牌然后渲染到 UI 的对象数组中。我有一个生成器类来获取数据,并将所有内容存储在一个状态对象中。我想知道这是否可能与异步功能有关,因为所有这些对我来说都很新。
export const shuffle = (array) => {
let currentIndex = array.length;
let temporaryValue;
let randomIndex;
const newArray = array.slice();
// While there remains elements to shuffle...
while (currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// Swap it with the current element.
temporaryValue = newArray[currentIndex];
newArray[currentIndex] = newArray[randomIndex];
newArray[randomIndex] = temporaryValue;
}
return newArray;
};
这是我也调用 shuffle 函数的其他代码
/* Global state of the app
*/
const state = {};
const startGame = async() => {
// 1) New Generator and add to state
state.generator = new Generator();
// 2) Prepare UI for Rendering
renderer.clearContent();
// 3) Call API for new User
await state.generator.generateUser();
// 4) Render user to UI
renderer.renderResults(state.generator.user);
// 5) Start a timer
$("#CountDownTimer").TimeCircles().start();
// When Timer hits 0 -------------->
$("#CountDownTimer").TimeCircles().addListener(function(unit, value, total) {
if (total < 0) {
//1) Clear HTML Content and Stop Timer
elements.playGround.innerHTML = "";
$("#CountDownTimer").TimeCircles().stop();
//2) shuffle Person Object
shuffle.shuffle(state.generator.user);
console.log(state.generator.user)
//3) Display Image
}
});
}
timer.displayTimer();
elements.startButton.addEventListener('click', element => {
element.preventDefault();
startGame();
})
解决方案
请注意您的shuffle
函数返回新数组,但是当您调用它时,shuffle.shuffle(state.generator.user);
您不会将返回值分配给任何内容......
尝试类似:
state.generator.user = shuffle.shuffle(state.generator.user);
推荐阅读
- android - 如何从 Kotlin 中的服务器正确获取 XML
- java - 如何将整数字节数组转换为编码为“ISO-8859-1”的字符串?
- python - 如何从图像中提取椭圆轮廓并保存到不同的变量中?
- python - 如何使用 exec 将 numpy 数组分配给字符串变量?
- javascript - 通过键值从Javascript中的嵌套数组对象中删除项目
- c++ - 唯一指针 - 为什么析构函数被调用 3 次
- javascript - 在 div 中提交显示复选框值后
- microsoft-teams - MS Teams 应用程序在移动客户端上显示 Intranet 作品,但在 Windows 上不显示
- elasticsearch - 应用分析器/过滤器时搜索弹性搜索错误
- flutter - Flutter - StreamBuilder - 刷新