数组中的随机文本字符串

Random string of text from an array

本文关键字:文本 字符串 随机 数组      更新时间:2023-09-26

我正在尝试获取一个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;

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

您正在以正确的方式获得随机值,但问题是第3行发生了什么。

var postmessage = + myArray;

在数组前面放一个+符号会试图把它变成一个数字,所以做+ myArray会得到NaN,这可能不是你想要的。

我猜你可能想把这个随机短语存储在邮件中。相反,它看起来像:

var postmessage = rand;

我认为你是偶然犯了一个简单的错误。您正试图将数组添加到变量中。我想你想添加随机选择的元素,所以你想在第三行:

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>