1

I borrowed this script (which had 3 pages) and added another 2 pages. The problem is that it only randomizes between the first 3 on the list. I don't quite undertand the ternary if/else either. If n is greater than 3, it's 0. Else if n is greater than 8, it's 1. Else 2? Did I get that right? It seems like a weird way to do it. How would I get it to randomize between 1 and 5?

<script type="text/javascript">
(function(n){
 var pages = ['Happy.html', 'Sad.html', 'Pensive.html', 'Eager.html', 'Inquisitive.html'];
 n = n < 3? 0 : n < 8? 1 : 2;
 window.location.replace(pages[n]);
})(Math.floor(Math.random() * 10));
</script>
MPelletier
  • 16,256
  • 15
  • 86
  • 137
  • 1
    `Math.floor(Math.random()*5)+1)` - forget about the ternary, there has obviously been some kind of logic behind it - _for the page you borrowed the script from_ ... – davidkonrad Sep 05 '13 at 14:53

3 Answers3

1

Do this:

<script type="text/javascript">
(function(n){
 var pages = ['Happy.html', 'Sad.html', 'Pensive.html', 'Eager.html', 'Inquisitive.html'];
 window.location.replace(pages[n]);
})(Math.floor(Math.random() * 5)); // Gets a random number between 0 and 4
</script>

or call this function borrowed from here:

<script type="text/javascript">

function randomFromInterval(from, to)
{
    return Math.floor(Math.random() * (to - from + 1) + from);
}

(function(n){
 var pages = ['Happy.html', 'Sad.html', 'Pensive.html', 'Eager.html', 'Inquisitive.html'];
 window.location.replace(pages[n - 1]);
})(randomFromInterval(1, 5)); // Gets a random number between 1 and 5
</script>
Community
  • 1
  • 1
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
  • D'oh! It doesn't actually redirect the page. The code makes more sense to me. I guess the original must have been a weighted probability. – user1815584 Sep 05 '13 at 15:01
1

you dont need the ternary operator.. you can just do this

function(n){
//everything except the ternary operator
}(Math.floor(Math.random()*10)%5)

The output of this expression is randomly between 0 and 4. not 1 and 5. this is required because the index of the array of 5 elements is between 0 and 4 inclusive.

Shikhar Subedi
  • 606
  • 1
  • 9
  • 26
1

In order to completely understand the ternary statement you presented, you need to know about Operator Precendence in JavaScript.

Take a look at this document: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

You got it right about how the ternary statement is going to be executed.

 n = n < 3? 0 : n < 8? 1 : 2;

can be translated into

if (n < 3) {
  n = 0;
}
else if (n < 8) {
  n = 1;
}
else {
  n = 2;
}

So it is more clear to understand what is going on.

And, here is how you get random int.

function randInt(n, min) {
  return (Math.floor(Math.random() * n)) + (min || 0);
}
var r = randInt(5, 1); // get random number from 1 to 5
Joon
  • 9,346
  • 8
  • 48
  • 75