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

114
Visualizações
Set Trap execute for two times - JS Proxy

Im working with proxies in js, but something is weird =>

let _usernames = [];

_usernames = new Proxy(_usernames, {
  set(target, prop, val) {
    console.count(); //this execute for two times!
    if(typeof val === 'string') {
      target[prop] = val;
      return true;
    } else {
      return false;
    }
  }
});

_usernames.push('Manuel');

The Set trap should call only once when i push to the array, but it executed twice.

And there is an error in the console, when i push to array =>

Uncaught TypeError: proxy set handler returned false for property '"length"'

How can i fix this and what's wrong?

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

0

Calling Array#push causes set to be called two times:

  1. target=[], prop=0, val=Manuel: Adds a new value to an index
  2. target=["Manuel"], prop=length, val=1: Updates length of array

In your case, the second call is returning false since the length value is numeric.

A possible solution:

let _usernames = [];

_usernames = new Proxy(_usernames, {
  set(target, prop, val) {
    console.log(target, prop, val);
    if(typeof val === 'string' || prop === 'length') {
      target[prop] = val;
      return true;
    } else {
      return false;
    }
  }
});

_usernames.push('Manuel');

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