[英]how can i generate one letter with javascript
function myFunction() { var x = document.getElementById("demo"); var alhpabet = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ"]; x.innerHTML = Math.floor((Math.random() * alhpabet.lengthS)); }
<button onclick="myFunction()">Try it</button> <p id="demo"></p>
How can I generate one letter with javascript? 如何使用javascript生成一个字母?
You could try this: 你可以试试这个:
function myFunction() { var x = document.getElementById("demo"); var min = "A".charCodeAt(0); var max = "Z".charCodeAt(0); var c = String.fromCharCode(Math.floor(Math.random() * (max - min)) + min); x.innerHTML = c; }
<button onclick="myFunction()">Try it</button> <p id="demo"></p>
You're nearly there. 你快到了。
Your Math.floor function gets a random index , but not the letter. 您的Math.floor函数获取随机索引 ,但不是字母。 Also, your 'array' wasn't actually an array, you need each letter in quotes, separated by a comma. 此外,你的'数组'实际上不是一个数组,你需要引号中的每个字母,用逗号分隔。 Alternatively, you can call split
on a string but lets ignore that for now. 或者,您可以在字符串上调用split
,但暂时忽略它。
Once you have the index, you can return the letter found at that index by putting alphabet[index]
. 获得索引后,可以通过输入alphabet[index]
返回在该索引处找到的alphabet[index]
。
Also, I'm sure you saw the comments but lengthS
should be length
. 另外,我确定你看到了评论,但lengthS
应该是length
。 And technically alhpabet
should be alphabet
. 技术上alhpabet
应该是alphabet
。
function myFunction() { var x = document.getElementById("demo"); var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]; var index = Math.floor((Math.random() * alphabet.length)); x.innerHTML = alphabet[index]; }
<button onclick="myFunction()">Try it</button> <p id="demo"></p>
You are almost done. 你差不多完成了。 As you have created alphabet
variable as an array, you should use the only first alphabet[0]
: 由于您已将alphabet
变量创建为数组,因此应使用唯一的第一个alphabet[0]
:
function myFunction() { var x = document.getElementById("demo"), alphabet = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ"], random = Math.floor(Math.random() * alphabet[0].length); x.innerHTML = alphabet[0][random]; }
<button onclick="myFunction()">Try it</button> <p id="demo"></p>
Basically you need a string and not an array with a string inside. 基本上你需要一个字符串而不是一个里面有字符串的数组。 Then take length
propery for multiplying the random number. 然后取length
来乘以随机数。
For the result take the random value as index for the string to get a single letter. 对于结果,将随机值作为字符串的索引来获取单个字母。
function myFunction() { var x = document.getElementById("demo"), abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; x.innerHTML = abc[Math.floor((Math.random() * abc.length))]; }
<button onclick="myFunction()">Try it</button> <p id="demo"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.