Brian
Brian

Reputation: 9

Random string of text from an array

I am trying to get a JavaScript code to select a string of text at random from an array. This is what I have so far but it doesn't seem to be working, appreciate the help. Don't know if this matters but this is for a website.

var myArray = ['One does not simply click the acorn'.'acorn spices all the rage with Martha Stewart', 'Once more into the acorn tree my friends','Acornbook launches as first acorn based social media']; 
var rand = myArray[Math.floor(Math.random() * myArray.length)];
var postmessage = + myArray;

Upvotes: 0

Views: 121

Answers (4)

D G ANNOJIRAO
D G ANNOJIRAO

Reputation: 58

<script>
var postmessage = ''; // initialization for getting the random selected text from array
var myArray = ['One does not simply click the acorn', 'acorn spices all the rage with Martha Stewart', 'Once more into the acorn tree my friends', 'Acornbook launches as first acorn based social media']; 
var rand = myArray[Math.floor(Math.random() * myArray.length)];
var postmessage =  rand;
</script>

Upvotes: 0

Daniel K.
Daniel K.

Reputation: 1566

I think you made a simple mistake by accident. You are trying to add an array to a variable. I assume you wanted to add the randomly picked element so you would want on the third line:

var postmessage = + rand;

Upvotes: 0

Dan Prince
Dan Prince

Reputation: 29989

You're getting the random value in the correct way, but the issue is what happens on line 3.

var postmessage = + myArray;

Putting a + sign in front of an array will try to turn it into a number, so doing + myArray results in NaN which is probably not what you wanted.

I'm going to guess that you probably wanted to store the random phrase in post message. Which would instead look like:

var postmessage = rand;

Upvotes: 0

Hanzallah Afgan
Hanzallah Afgan

Reputation: 734

You are using the dot "." instead of comma "," among the very first two elements in myArray. You should use comma there as below.

var myArray = ['One does not simply click the acorn','acorn spices all the rage with Martha Stewart', 'Once more into the acorn tree my friends','Acornbook launches as first acorn based social media'];

Upvotes: 2

Related Questions