首页 > 解决方案 > 随机播放对象数组无法按预期工作

问题描述

随机播放对象数组无法按预期工作

我已经尝试了在这里找到的所有不同类型的随机播放方法。如果我在 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();
})

标签: javascriptarraysobjectasync-await

解决方案


请注意您的shuffle函数返回数组,但是当您调用它时,shuffle.shuffle(state.generator.user);您不会将返回值分配给任何内容......

尝试类似:

state.generator.user = shuffle.shuffle(state.generator.user);

推荐阅读