2017-12-18 189 views
1

我有一个非常简单的页面(下面复制了整个东西),加载时,随机将用户重定向到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> 

+1

'Math.ceil(Math.random()* 7)'可以是'7',它是你数组的长度。 – Titus

回答

2

而不是

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

你需要的是

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

随着ceil的最后一个项目将永远是不存在的,因为这将是相等的长度阵列。在一个数组中,索引从0开始。所以你需要使用floor

+0

这个技巧。谢谢你,感谢你的解释! – Justin