A. Berg A. Berg - 28 days ago 20
HTML Question

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?

Answer

You're nearly there.

Your Math.floor function gets a random index, but not the letter. 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.

Once you have the index, you can return the letter found at that index by putting alphabet[index].

Also, I'm sure you saw the comments but lengthS should be length. And technically alhpabet should be 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>