数组中的随机文本字符串
Random string of text from an array
我正在尝试获取一个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>
相关文章:
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- 将html元素插入到文本字符串中,以匹配另一个html字符串
- 转换<a>使用jQuery将文本字符串转换为dom元素
- 数组中的随机文本字符串
- Javascript-使用“”将toDateStringMonth从文本字符串解析为数字字符串;如果“;vs“;开关”;
- javascript高亮文本字符串
- 当用户单击按钮(在光标位置)时,在输入字段中添加一个文本字符串
- 函数输入上未终止的文本字符串
- 跳过用户输入的文本字符串中的特殊字符,并在 Javascript 中的每个单词后添加连字符
- 如何使用javascript验证文本字符串
- 将部分文本字符串转换为html
- 如何使用javascript在单个正则表达式中递归替换文本字符串中重复的逗号
- 使用PowerShell在JavaScript网页上搜索文本字符串
- 使用jquery感知文本字符串中的时间范围
- 匹配最后一个点之后的文本字符串
- 从段落中删除某些文本字符串
- 如何使用 javascript 将输入到文本框中的变量插入到文本字符串中
- 当页面上存在特定文本字符串时发送 Google Analytics(分析)事件
- JSON 处理 - 向 JSP 发送 JSON 文本字符串,如何在 JSP 中处理
- 如何使用 JavaScript(但不是标签或属性)替换字符串中所有匹配的纯文本字符串