【问题标题】:There is something wrong with my randomized link我的随机链接有问题
【发布时间】:2017-12-18 12:18:35
【问题描述】:

我有一个非常简单的页面(下面复制了整个内容),在加载时,它会随机将用户重定向到 7 篇文章中的一篇。一篇文章(链接列表中的最后一篇)每次都会导致 404 错误,我不知道为什么。复制并粘贴到浏览器中时,该链接可以正常工作。任何能指出问题所在的帮助都会很棒,谢谢。

<!DOCTYPE HTML>
<html>
<head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-34602317-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-34602317-1');
    </script>

    <title>Words That Kinda Matter</title>
    <meta charset="utf-8" />
    <script type="text/javascript">
        var pageArr = ["https://medium.com/@olivershiny/eb47cffd04f1", "https://medium.com/@manfraiya/a2a3fcfd046c", "https://medium.com/@sravss/43f43d67593c", "https://medium.com/@rachaelflanery/9d457ba9a357", "https://medium.com/@benjaminsledge/9a19b7f85dfb", "https://medium.com/@writingsolo/7dac9351cd57", "https://medium.com/@justincox/46342de79f68"];
        document.location.href = pageArr[Math.ceil(Math.random()*7)];
    </script>
</head>
<body>



</body>

【问题讨论】:

  • Math.ceil(Math.random()*7) 可以是 7,这是您的数组的长度。

标签: javascript html random


【解决方案1】:

代替

document.location.href = pageArr[Math.ceil(Math.random()*7)];

你需要的是

document.location.href = pageArr[Math.floor(Math.random()*7)];

对于ceil,最后一项将始终不存在,因为它将等于数组的长度。在数组中,索引从 0 开始。所以你需要使用 floor

【讨论】:

  • 成功了。谢谢你,谢谢你的解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多