我正在尝试获取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 :(得分: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'];
答案 1 :(得分:0)
我认为你偶然犯了一个简单的错误。您正在尝试将数组添加到变量中。我假设你想要添加随机选择的元素,所以你想在第三行:
var postmessage = + rand;
答案 2 :(得分:0)
您以正确的方式获取随机值,但问题出在第3行。
var postmessage = + myArray;
在数组前添加+
符号会尝试将其转换为数字,因此执行+ myArray
会导致NaN
,这可能不是您想要的。
我猜你可能想把这个随机短语存储在帖子中。相反的是:
var postmessage = rand;
答案 3 :(得分: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>