EdwardBlack EdwardBlack - 2 years ago 66
Javascript Question

Initialize array with variables: Unexpected token +

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];


But I get
Uncaught SyntaxError: Unexpected token +

Answer Source

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 that is binary and performs the OR operation over it. Finally the result will get converted back to the original base. Hence the decimal points will be removed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download