2015-03-31 41 views
0

我想要一個JavaScript代碼從數組中隨機選擇一個文本字符串。這是我迄今爲止的,但它似乎並沒有工作,感謝幫助。不知道這是否重要,但這是一個網站。隨機數組中的文本字符串

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; 
+0

具體什麼不工作?你做了什麼來調試它? – clearlight 2015-03-31 02:19:25

+0

@ntalbs - 太好了,您實際上是通過編輯修改了代碼。 – 2015-03-31 02:19:37

回答

2

您正在使用點「。」。而不是逗號「,」在myArray的前兩個元素中。 您應該在下面使用逗號。

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']; 
+0

儘管@ntalbs更改了代碼,但您的回答是正確的。 – 2015-03-31 02:20:18

0

我認爲你犯了一個簡單的意外錯誤。您正在嘗試將數組添加到變量。我假設你想添加隨機挑選的元素,所以你會希望在第三行:

var postmessage = + rand; 
+1

在'var'語句之後,你實際上不能使用'+ ='運算符。當您嘗試調用加法運算符時,該變量將沒有值。這可能會導致語法錯誤。 – 2015-03-31 02:33:26

+0

@DanPrnce thx,很高興你抓到了!我也習慣Java! – 2015-03-31 03:02:13

0

你得到正確的方式隨機值,但問題是上線會發生什麼3.

var postmessage = + myArray; 

把一個+標誌在陣列前面會盡量把它變成一個數字,這樣做+ myArray結果NaN這可能不是你想要的。

我猜你可能想將隨機詞組存儲在郵件中。這反而會看起來像:

var postmessage = rand; 
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> 
相關問題