简体   繁体   English

数组中的随机文本字符串

[英]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. 我正在尝试获取JavaScript代码以从数组中随机选择文本字符串。 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;

You are using the dot "." 您正在使用点“。” instead of comma "," among the very first two elements in myArray. 在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'];

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;

You're getting the random value in the correct way, but the issue is what happens on line 3. 您以正确的方式获得了随机值,但是问题在于第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. 在数组前面放置一个+号会尝试将其转换为数字,因此执行+ myArray导致NaN ,这可能不是您想要的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM