【问题标题】:Shuffle array of objects doesn't work as expected随机播放对象数组无法按预期工作
【发布时间】:2019-01-13 18:18:00
【问题描述】:

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

我已经尝试了在这里找到的所有不同类型的随机播放方法。如果我在 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 后会记录什么值?您的意思是再次拨打renderer.renderResults(state.generator.user); 吗?

标签: javascript arrays object async-await


【解决方案1】:

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

尝试类似:

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

【讨论】:

    【解决方案2】:

    您的 shuffle 方法是不可变的,并且您在调用它时没有使用它的返回值。

    删除此行:const newArray = array.slice(); 并将newArray 替换为array

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 2022-06-13
      • 1970-01-01
      相关资源
      最近更新 更多