Reputation: 34
For school I need to make a script that prints 3 times something with 5 random letters. "ajshw kcmal idksj"
I have made this:
var myArray = ['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 random = myArray[Math.floor(Math.random() * myArray.length)];
document.write('<br>' + random);
But this only prints one letter. How can it print 5 letters 3 times?
Upvotes: 0
Views: 498
Reputation: 1542
A simple way would be to simply generate that single letter multiple times with a loop. A way to do this would go as follows:
var myArray = ['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 phrase = "";
for (var x = 0; x < 3; x++) {
for (var y = 0; y < 5; y++) {
phrase = phrase + myArray[Math.floor(Math.random() * myArray.length)];
}
phrase = phrase + " ";
}
console.log(phrase)
Upvotes: 0
Reputation: 26315
What about just making a nested loop:
const myArray = ['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'
];
const length = myArray.length;
const numStrings = 3;
const numLetters = 5;
for (let i = 0; i < numStrings; i++) {
let string = "";
for (let j = 0; j < numLetters; j++) {
let letter = myArray[Math.floor(Math.random() * length)];
string += letter;
}
console.log(string);
}
Upvotes: 0
Reputation: 22524
Iterate 5 times to generate each word with 5 letters and iterate 3 times to generate three words. You can use for
loop to generate the words or you can use array#map
to generate the words and using array#join
you can join them.
var myArray = ['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'],
random = [...Array(3)]
.map(_ => [...Array(5)].map(_ => myArray[Math.floor(Math.random() * myArray.length)]).join(''))
.join('<br>');
document.write(random);
Upvotes: 1