2016-11-09 60 views
1

怎样才能与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>

怎样才能用JavaScript一个字母?

+0

你还需要这封信被插入到'demo'元素? – damienc

+2

'alhpabet.lengthS'>'alhpabet.length' – Roberrrt

回答

1

你快到了。

您的Math.floor函数获取随机索引,但不是字母。另外,你的'数组'实际上不是一个数组,你需要引号中的每个字母,用逗号分隔。另外,你可以在字符串上调用split,但现在让我们忽略它。

一旦你有了索引,你就可以通过把alphabet[index]返回在该索引处找到的字母。

此外,我相信你看到了评论,但lengthS应该是length。而技术上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>

1

你可以试试这个:

\t function myFunction() { 
 
    \t \t var x = document.getElementById("demo"); 
 
\t \t var min = "A".charCodeAt(0); 
 
\t \t var max = "Z".charCodeAt(0); 
 
\t \t var c = String.fromCharCode(Math.floor(Math.random() * (max - min)) + min); 
 
    \t x.innerHTML = c; 
 
\t \t }
<button onclick="myFunction()">Try it</button> 
 
\t \t \t <p id="demo"></p>

1

您应该使用ASCII。大写字母的范围是65-90。

function myFunction() { 
    var x = document.getElementById("demo"); 
    var charCode = Math.floor(Math.random() * (90 - 65 + 1)) + 65; 
    x.innerHTML = String.fromCharCode(charCode); 
} 
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>

0

基本上你需要一个字符串,而不是一个字符串里的数组。然后采取length propery乘以随机数。

对于结果,将随机值作为字符串的索引以获取单个字母。

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>

+1

您正在打印出一个数字,但不是OP中询问的字母 –

相关问题