Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

477
Visualizações
Random Letter Generator

I'm a total newb here learning how to code :) Hoping someone can shed some light on the following.

I'm writing some code in JavaScript to generate a random mix of 6 letters from the alphabet using a Math.random method and a for-loop.

I can get this to work when I write the code 'Math.floor(Math.random() * alphabet.length)' directly into the array index however when I assign it to a variable and use that as the index instead, I end up with a 'random' letter that's duplicated 6 times.

Is it possible to assign a random value (using the Math.random method) to a variable and have it execute each time it goes through the loop? Thanks in advance!

This is the code that works:

var alphabet = "abcdefghijklmnopqrstuvwxyz";
var randomString = "";

for (var i = 0; i < 6; i++) {
randomString += alphabet[Math.floor(Math.random() * alphabet.length)];

console.log(randomString);
}

Output code example: xuhmwg

This code ends up with duplicated letters:

var alphabet = "abcdefghijklmnopqrstuvwxyz";
var randomString = "";
var randomNumber = Math.floor(Math.random() * alphabet.length);

for (var i = 0; i < 6; i++) {
randomString += alphabet[randomNumber];

console.log(randomString);
}

Output code example: dddddd

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I would do it like this:

function getRandomString(length) {
  const alphabet = "abcdefghijklmnopqrstuvwxyz";
  let randomString = ''
  for (let i = 0; i < length; i++) {
    randomString += alphabet[Math.floor(Math.random() * alphabet.length)]
  }
  return randomString
}

console.log(getRandomString(6))

This gives you the freedom to easily change the length of your generated code, and change your alphabet (you can add symbols for example).

about 4 years ago · Juan Pablo Isaza Relatório

0

This is how I would do it.

var alphabet = "abcdefghijklmnopqrstuvwxyz";
var randomString = "";

for (var i = 0; i < 6; i++) {
randomString += alphabet[Math.floor(Math.random() * alphabet.length)];
console.log(randomString);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda