0

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;
2
  • What specifically is not working? What have you done to debug it? Commented Mar 31, 2015 at 2:19
  • @ntalbs - Great, you actually changed the code with your edit. Commented Mar 31, 2015 at 2:19

4 Answers 4

2

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'];
Sign up to request clarification or add additional context in comments.

1 Comment

Even though @ntalbs changed the code, you answer was correct.
0

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;

Comments

0

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;

1 Comment

You can't actually use the += operator after a var statement. The variable will have no value when you try to call the addition operator. This is probably going to result in a Syntax error.
0
<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.