【问题标题】:Random function on each time page load每次页面加载时的随机函数
【发布时间】:2017-01-15 16:24:24
【问题描述】:

我有一些功能:

fbFetch();
fbFetch1();
fbFetch2();
fbFetch3();
fbFetch4();

我想在页面加载时触发随机函数。

【问题讨论】:

    标签: javascript function random


    【解决方案1】:
    var fns = [fbFetch, fbFetch2, fbFetch /* ...you get the idea */]
    var selectedFn = Math.floor(Math.random() * fns.length);
    body.addEventListener("load", fns[selectedFn], false);
    

    【讨论】:

    【解决方案2】:

    将函数推入数组,然后使用随机索引调用其中一个:

    var a = [];
    a.push(fbFetch);
    a.push(fbFetch1);
    //...
    
    var index = parseInt(Math.random() * a.length);
    a[index]();
    

    【讨论】:

    • 它们的结果相同。我想到的第一件事就是使用parseInt
    • Math.random 永远不会返回 1。在我的回答下查看我的评论。
    【解决方案3】:

    将函数放入数组并用数学随机触发它。

    var arr = ['fbFetch();','fbFetch1();','fbFetch2();','fbFetch3();','fbFetch4();'];
    var ran = Math.floor(Math.random() * 6) + 1
    
    $(document).ready(arr[ran]());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-15
      • 2014-02-09
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2015-04-09
      相关资源
      最近更新 更多