随机链接javascript以忽略当前页面

Random link javascript to ignore current page

本文关键字:当前页 链接 javascript 随机      更新时间:2024-03-08

当我点击导航栏(引导程序)上的"随机"链接时,它指的是Javascript代码(下面)将我带到模拟网站上的随机页面。

然而,我想添加一个功能,所以如果我在,比如Link[2]=fed-rates.html,当我按下导航栏上的"随机"链接时,它总是会让我离开当前所在的页面(也就是说,它会忽略链接[2])。

我想知道这是否可能,如果能得到一些想法就太好了。

Javascript代码:

function randomlinks(){
    var myrandom=Math.round(Math.random()*2)
    var links=new Array()
    links[0]="articles/how-to-trade-oil.html"
    links[1]="articles/usd-yen-gbp.html"
    links[2]="articles/fed-rates.html"
    window.location=links[myrandom]
}
// above is for all web pages
function randomlinksarticle(){
    var myrandom=Math.round(Math.random()*2)
    var links=new Array()
    links[0]="how-to-trade-oil.html"
    links[1]="usd-yen-gbp.html"
    links[2]="fed-rates.html"
    window.location=links[myrandom]
}
// above is so navbar link still works on the linked pages, with the way I have the folder directory setup

出现"/未定义"页面的新代码:

function randomlinksarticle(){
var myrandom=Math.round(Math.random()*2)
var links=new Array()
links[0]="how-to-trade-oil.html"
links[1]="usd-yen-gbp.html"
links[2]="fed-rates.html"
links.forEach(function(link, index) {
if (location.href.indexOf(link) !== -1) {
    links.splice(index, 1);
}});
window.location=links[myrandom]

您可以执行以下操作:

links.forEach(function(link, index) {
    if (location.href.indexOf(link) !== -1) {
        links.splice(index, 1);
    }
});

这会查看所有链接,并检查它们是否存在于当前URL中。如果是,则会使用拼接功能将它们从列表中删除。

在设置链接[2]后添加此代码,因为此时应该删除当前页面。


编辑:我还注意到你的随机函数不是均匀分布的。这并不重要,但它可能会给你带来问题。原因是0和2之间的数字比0或2要多得多。为了从你的随机数刻度中得到一个零,Math.random()必须小于0.5。同样,它必须大于或等于1.5才能得到2。0和2的概率为0.5/2或1/4。这留下了获得1的1/2概率,这是有道理的,因为所有0.5到1.5之间的数字都会给你1。

tl;dr:使用math.floor(Math.random() * (maximum + 1))而不是Math.round(Math.random() * maximum)来生成随机数。


此外,如果你想用一种不那么重复的方法来做这件事,你可以用这两个函数来代替这样的东西:

function randomLink() {
    var links = Array.prototype.slice.call(arguments, 0); //Turns the function's arguments into an array
    links.forEach(function(link, index) { //Loops through all the links
        if (location.href.indexOf(link) !== -1) { //If the link text is contained in the url
            links.splice(index, 1); //Remove the link from the links array
        }
    });
    var rand = Math.floor(Math.random() * links.length); //Choose a number between 0 and links.length - 1
    window.location = links[rand]; //Visit the link
}

您可以用任意数量的页面将其称为randomLink("first_page.html", "second_page.html")