-1

I created a simple function which should initialize an array and return one random element from it everytime when the function is called.

function test(str)
{
    var myArray = 
    {
        "Test1 "+ str + " Test1",
        "Test2 "+ str+ " Test2"
    }

    return myArray[Math.random()*myArray.length+0];
}

console.log(test("FOO"));

But I get Uncaught SyntaxError: Unexpected token +

Black
  • 18,150
  • 39
  • 158
  • 271

2 Answers2

2

Use [ ] instead of { } for a JS Array.

function test(str)
    {
        var myArray =
                [
                    "Test1 "+ str + " Test1",
                    "Test2 "+ str+ " Test2"
                ]

        return myArray[parseInt(Math.random()*myArray.length, 10)];
    }
Aboelseoud
  • 556
  • 1
  • 7
  • 22
2

Here in your code myArray is not an array,

function test(str){
    var myArray = ["Test1 " + str + " Test1","Test2 " + str + " Test2"] 
    return myArray[(Math.random() * myArray.length) | 0];
}

| This is bit wise OR operator. When doing operand1 | operand2, both the operands will get converted to base 2 and performs the OR operation over it. Finally the result will get converted back to the base 10. Hence the decimal points will be removed.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • This is the best solution i think. – Black Apr 22 '16 at 12:01
  • @EdwardBlack Glad to help! :) – Rajaprabhu Aravindasamy Apr 22 '16 at 12:03
  • Yes! Nice solution.. Just explain `|` :) – Rayon Apr 22 '16 at 12:03
  • "*converted to base 2 that is binary*" is confusing, if not wrong. Yes, the number will be converted to a 32 bit integer, but everything on a computer is "binary". And there is no "*original base*", it's a floating point number. – Bergi Apr 22 '16 at 12:10
  • @Bergi Corrected the things that you said. But base 2 numbers cannot be told as binary? I have a confusion on this. – Rajaprabhu Aravindasamy Apr 22 '16 at 12:14
  • Oh, sure "binary" can mean the same as "base 2", just like "decimal" stands for "base 10". But every number on a computer really already is in a binary format - unless it is stored in a string - so this "base conversion" is meaningless. What really happens is a conversion from floating point to integer format, which strips the decimal digits. Or just use `Math.floor`, then you don't have to [explain](http://stackoverflow.com/q/9049677/1048572) [anything](http://stackoverflow.com/q/7487977/1048572). – Bergi Apr 22 '16 at 12:27