首页 > 解决方案 > 如何以随机顺序运行一组函数

问题描述

我想以随机顺序运行 4 个函数。不知道从哪里开始。这是我的代码,没有随机顺序。

generate.addEventListener('click', generateclick)

function generateclick(){
fifth()
fourth()
majthird()
minthird()
}

标签: javascripthtmlfunctionmathrandom

解决方案


function getRandomIntFromArr(array) {
  return array[Math.floor(Math.random() * array.length)];
}

const funMap = {
  1: () => {
    console.log("1 fun called");
  },
  2: () => {
    console.log("2 fun called");
  },
  3: () => {
    console.log("3 fun called");
  },
  4: () => {
    console.log("4 fun called");
  },
};

let array = [1, 2, 3, 4];

for (let i = 0; i < 4; i++) {
  let j = getRandomIntFromArr(array);
  funMap[`${j}`]();
  array = array.filter((el) => el !== j);
}


推荐阅读