javascript - 如何以随机顺序运行一组函数
问题描述
我想以随机顺序运行 4 个函数。不知道从哪里开始。这是我的代码,没有随机顺序。
generate.addEventListener('click', generateclick)
function generateclick(){
fifth()
fourth()
majthird()
minthird()
}
解决方案
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);
}
推荐阅读
- emulation - WAN Emulator 软件可调整 ISP 延迟、丢包和抖动以测试 SD-WAN
- c# - 从异步方法显示表单并等待结果会导致出现额外的空白表单
- qt - 将 QQmlApplicationEngine 渲染保存到 SVG
- node.js - 运行二进制文件和使用 npm 从 package.json 运行脚本有什么区别?
- java - 使用自定义样式初始化 Spinner 时单击 Spinner 项目时没有任何反应
- jmeter - 在终端运行测试后无法打开 .jtl Jmeter 结果
- c# - 组合框单击了相同的元素
- javascript - 开玩笑模拟调用真实客户端而不是模拟
- python - 使用 WLST 为自定义 MBean 设置 javax.management.openmbean.CompositeDataSupport 属性
- android - 如何通过单击 ListView 上的特定 ImageView 来调用地图位置意图