Search code examples
javascripthtmlrandom

There is something wrong with my randomized link


I have a very simple page (entire thing copied below) that, upon loading, randomly redirects the user to one of 7 articles. One article (the last one in the list of links) causes a 404 error every time and I cannot figure out why. The link works fine when copied and pasted into the browser. Any help pointing out what is goofing up would be wonderful, thank you.

<!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>


Solution

  • Instead of

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

    what you need is

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

    With ceil the last item will always be non existent as it will be equal to the length of the array. In an array indices start from 0. So you will need to use floor