Reputation: 31
My case:
function randomLetter(){
var random = letter[Math.floor(Math.random()*26)];
return random;
}
function randomWord(wordLength){
var random = randomLetter() + randomLetter() + randomLetter();
return random;
}
How do I write a code that run the randomLetter()
function x times using parametes.
Example: I write 3 in the parameter, and the function will give me three random letters.
So instead of writing randomLetter() + randomLetter() + randomLetter()
, I will just write randomWord(3)
, and I will get three random letters.
Upvotes: 0
Views: 54
Reputation: 6872
Yet another recursive solution:
function randomLetter() {
return ('qwertyuiopasdfghjklzxcvbnm')[Math.floor(Math.random()*26)];
}
function randomWord(wordLength) {
return (wordLength > 0) ? (randomWord(wordLength - 1) + randomLetter()) : '';
}
console.log( randomWord(10) );
Upvotes: 0
Reputation: 501
You can use a for-loop:
function randomWord(x){
var random = [];
for(var a = 0; a < x; a++){
random[a] = randomLetter();
}
return random.join("");
}
Upvotes: 0
Reputation: 589
For this you could use a for loop like:
function randomWord(wordLength){
var random =''
for (var i = 0, i<wordLength, i++) {
random += randomLetter();
}
return random;
}
the first parameter in the parentheses after the 'for' keyword initializes the i variable with 0. The next value i<wordLength
is the stop condition, which will test at the beginning of each run if the condition is still true, otherwise it will stop looping. The third i++
is what runs every time a loop finishes, in this case it increments i by one, which is identical to i = i + 1
.
here is some more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
Upvotes: 0
Reputation: 1187
Or recursion:
var letters = "abcdefghijklmnopqrstuvwxyz"
function randomLetter() {
return letters.charAt(Math.floor((Math.random() * 100)) % letters.length)
}
function getLetters(count) {
if (count-- < 1) return "";
return getLetters(count) + randomLetter() + ","
}
document.getElementById("output").innerText = getLetters(4)
<div id="output" />
Upvotes: 0
Reputation: 423
Another approach, which buffers each letter into an array and returns the joined array.
function randomWord(wordLength){
var letters = [];
for (var i = 0; i < wordLength; i++) {
letters.push(randomLetter());
}
return letters.join("");
}
Upvotes: 1