-4

So my Javascript code is supposed to randomly pick, but it always picks the first option, even if I switch the options, it always goes to the one on top. Did I make an error, or how can I get this to work?

function test() {
     var values = ["1","2"],
        valueToUse = values[Math.floor(Math.random() * values.length)];
    // do something with the selected value
    alert(valueToUse);
} 

if (values = 1) {
window.location = "tail.html"; }
else if (values = 2) { window.location = "head.html"; }

4 Answers4

6
if (values = 1) {

That's an assignment, not a comparison (===). It will always be true.


Additionally, you never call test().


Additionally, you should be testing valueToUse not values, since that is where you assign your random choice.


Additionally, both valueToUse and values are locally scoped to the test() function and are not available outside it. Your assignment creates a new, global variable.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

You need to use == (or ===) instead of =.

if (values == 1) {
  // and so on...
}
chrki
  • 6,143
  • 6
  • 35
  • 55
1

Well, for the start if (values = 1) is not the valid way to compare. = annotates assignment so basically you are setting the value to 1. If you want to compare values in js, you do it this way if (values === 1).

In other programming language u usually use == instead however in js if you compare it this way it will only check the value not the type of the variable so a number 2 will match a string "2" if (2 == "2") {//result is true}.

If you use === it will check both the value and the type if (2 == "2") {//result is false}

Proxy
  • 1,118
  • 2
  • 10
  • 27
1

To make your code fly, you could return a random selected value from the array, store it in value and check it for the new direction. I omit window.location and us simply console.log for displaying the result of the comparison.

The comparison is strict, with a check for a string.

function test() {
    var values = ["1", "2"],
        valueToUse = values[Math.floor(Math.random() * values.length)];

    return valueToUse;
}

var value = test();

if (value === '1') {
    console.log( "tail.html");
} else if (value === '2') {
    console.log( "head.html");
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392