1
var links = ["http://www.google.com/", "http://www.cnn.com/", "http://www.bbc.com/", "http://www.nbc.com/"];
var random = Math.round(Math.random() * 4);
var previous = [];
previous.push(random);

for (var i = 0; i < previous.length; i++) {
    while (previous[i] == random) {
        random = Math.round(Math.random() * 4);
    }
}
window.location = links[random];

So I've got this here code. It's purpose is, once launched with a button on a google site, to lead the user to one of the set sites, randomly. What I need it to is to remember which site it takes them to (by remembering the Math.random output). Right now, each time the code is run (simulating a user clicking the button many times), it erases my memory array, 'previous'. I want this code to open a separate window for the site it outputs to. Whether cookies, iframes or some other method is used, I'd be very thankful if someone could help me out.

I'm currently going through the Codecademy course on Javascript, so please understand if I am missing something simple :)

Lillz
  • 283
  • 2
  • 5
  • 19

2 Answers2

2

you need a global previous.

use

var links = ["http://www.google.com/", "http://www.cnn.com/", "http://www.bbc.com/", "http://www.nbc.com/"];
var random = Math.round(Math.random() * 4);
window.previous = window.previous || [];
window.previous.push(random);

for (var i = 0; i < window.previous.length; i++) {
    while (window.previous[i] == random) {
        random = Math.round(Math.random() * 4);
    }
}
window.location = links[random];
Kamrul
  • 7,175
  • 3
  • 31
  • 31
  • Ok I put it into jsfiddle (http://jsfiddle.net/vrW2f/), but it doesn't seem to be keeping the values in the previous array each time I run it? – Lillz Jun 17 '14 at 22:27
  • This won't work; the variable on the `window` will go away when you navigate to a new page. – Ryan Erdmann Jun 17 '14 at 22:28
  • Well unless it brings a popup window instead of redirecting your page. I'm using this for google forms... When a user clicks the button, it will take them to a google form. They'll be clicking it multiple times so it'd be nice for no repeats. Google forms would look best with a new window opening, if possible. This would mean no cooies (I think?). – Lillz Jun 17 '14 at 22:31
  • it will work if you do not refresh the page. if you want keep the values even if you refresh the page, you have to use cookies/localstorage – Kamrul Jun 17 '14 at 22:33
  • try renaming the variable from `previous` to `myprevious` or something not conflickting – Kamrul Jun 17 '14 at 22:36
  • Again, it'll run in jsfiddle but it will still return to previously viewed sites – Lillz Jun 17 '14 at 22:43
  • See my answer below. There's a bug in the for/while loop that lets previously viewed sites get chosen. – Ryan Erdmann Jun 17 '14 at 22:45
0

You have a couple of problems with your solution:

  1. When you navigate to a different page (with window.location = ...), you lose any variables you have. It's impossible to keep your previous array if you navigate to a new page, even if you attach it to the window.
  2. Your for loop with a while isn't doing what you think. It should make sure you get a number you haven't used yet, but there's a bug: the inner while can choose a random number that is in the previous array after you've gone past in in the for. i.e. if previous = [0,2], when the for loop is checking that previous[1] == random, it could choose 0 as the new random number, even though it's the value of previous[0].
  3. You'll infy-loopy if you've visited all the links.

To fix this, first you have to start opening the pages in a new window. Refer to this SO answer for more information on how to do this.

Second, you need to do a better job of making sure that your previous array doesn't contain the value. A simple implementation of a contains function is:

function contains(array, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == value) return true;
    }
    return false;
}

Here's a working JS Fiddle of what you're looking for: http://jsfiddle.net/pnP4D/7/

I keep a visited array to store the links you've visited; you could just as easily keep this as your previous array and store random numbers.

var links = ["http://www.google.com/", "http://www.cnn.com/", "http://www.bbc.com/", "http://www.nbc.com/"];
var visited = [];

// Assumes you have an element like <button id='btn'>Click me</button>
var button = document.getElementById('btn');
button.addEventListener('click', function() {

    // If we've visited all the links, don't try redirecting again
    if (visited.length == links.length) {
        alert('You visited all the links');
        return;
    }

    // Variables to hold our random number and link
    var random, url;

    // Keep getting a new random url while it's one we've already visited
    do {
        random  = Math.round(Math.random() * 3);
        url = links[random];        
    } while (contains(visited, url));

    // We have a url we haven't visited yet; add it to the visited array
    visited.push(url);   

    // Open the link in a new window so we can hold on to the visited array in this window
    var win = window.open(url, '_blank');
    win.focus();
});

// A simple function to check if an array contains a value
function contains(array, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == value) return true;
    }
    return false;
}
Community
  • 1
  • 1
Ryan Erdmann
  • 1,786
  • 10
  • 11
  • Ok actuallly, one issue. All the sites open *except* whatever is in [0] in the array. This will open a blank tab... – Lillz Jun 17 '14 at 22:54
  • Glad I could help! Sorry about the mistake, there's another bug in the random number generation: it needs to be `Math.random() * 3`. http://jsfiddle.net/pnP4D/7/ – Ryan Erdmann Jun 18 '14 at 03:26
  • Thanks! I customized the button a bit too on revision 9. I just tried testing it on a google site, though. I'm not sure how exactly google likes it's html/css/js compiled, but I tried this: http://pastebin.com/uU6Pncgb and it seems to keep the default button (which is fine if it has to), but it also doesn't open new links... Any idea why? – Lillz Jun 18 '14 at 03:48
  • "It's impossible to keep your previous array if you navigate to a new page" is false, since you can use cookies/local storage/session storage. – Tiago Marinho Jun 18 '14 at 07:02