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

640
Visualizações
Get random element of dictionary in TypeScript?

I am trying to implement code that will return me a random element of a dictionary in TypeScript. So far, I've tried this:

dict = {
    0: "example 1",
    1: "example 2",
    2: "example 3"
  }

randomGen() { 
    var num = Math.floor(Math.random() * (3));
    console.log(this.dict[num])
  }

However this is throwing me an error:

Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{ 0: string; 1: string; 2: string; }

Is there a way around this? How can I randomly select an element from my dictionary?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Here you go. I use the dictionary you created and randomly select a number based on the length of the dictionary (which are your keys). Then return the value of the random key.

Here is for Typescript (test in https://www.typescriptlang.org/play):

var dict: {[key: number]: string} = {
    0: "example 1",
    1: "example 2",
    2: "example 3"
  }

function randomGen() { 
    var value = dict[Math.floor(Math.random() * Object.keys(dict).length)];
    return value;
  }
 
console.log(randomGen());

And below is for basic JavaScript:

var dict = {
    0: "example 1",
    1: "example 2",
    2: "example 3"
  }

function randomGen() { 
    var value = dict[Math.floor(Math.random() * Object.keys(dict).length)];
    return value;
  }
 
console.log(randomGen());

over 4 years ago · Santiago Trujillo 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