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

259
Visualizações
Trying to construct a variable name from a string and another variable name with window[] but not working

This is my code:

function test(tlm) { 
 var soundtimer = 'success';
 var type = tlm.replace('send','');
 var timer = window[type+'timer'];

 console.log(timer);
}

test('sendsound');

I should get success but I get undefined instead. Why is that?

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

0

Your 'soundtimer' variable is locally scoped to the test function. Moving it outside allows it to be globally declared on window:

var soundtimer = 'success';
function test(tlm) {
  var type = tlm.replace('send','');
  var timer = window[type+'timer'];

  console.log(timer);
}

test('sendsound');

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use an object within your function.

function test(tlm) { 
  var local = {
    soundtimer:'success'
  };
 var type = tlm.replace('send','');
 var timer = local[type+'timer'];

 console.log(timer);
}

test('sendsound');

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