A. Berg
A. Berg

Reputation: 11

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?

Upvotes: 1

Views: 123

Answers (5)

Nina Scholz
Nina Scholz

Reputation: 386620

Basically you need a string and not an array with a string inside. Then take length propery for multiplying the random number.

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>

Upvotes: 0

Djave
Djave

Reputation: 9329

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>

Upvotes: 1

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

You are almost done. As you have created alphabet variable as an array, you should use the only first 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>

Upvotes: 0

Kamil Latosinski
Kamil Latosinski

Reputation: 846

You should use ASCII. The range for uppercase alphabet letters is from 65-90.

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

Upvotes: 1

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>

Upvotes: 1

Related Questions