2017-12-18 187 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