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

158
Visualizações
How to execute this result within a limited function

Questions are as follows:
The first time you call the add, it will return 1;
the second time you call, it returns 2;
Can only be written in function

var add = function () {
     // start only 
    
     // end 
};
 
console.log(add()); // 1
console.log(add()); // 2

The current idea is that a global variable is needed
So the current way of writing
But this way of writing does not meet the requirements

var add = (function () {
 let counter=0
   return function () {
  counter += 1; return counter;}
}();

I don't know how to adjust the code to solve this question thank you

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

0

somethig like this?

var add = {
    time: 0,
    call: () => {
        add.time++;
        console.log(add.time);
    }
};

add.call(); // 1
add.call(); // 2

about 4 years ago · Juan Pablo Isaza Relatório

0

I'd do it like this. It implicitely creates a global variable, which is dirty as hell, but it meets the (strange) requirements.

var add = function () {
     if(typeof a === "undefined") a = 0;
     return ++a;
};
 
console.log(add()); // 1
console.log(add()); // 2

about 4 years ago · Juan Pablo Isaza Relatório

0

All the solutions that came to mind:

Use a property assigned to the function

// in JS, a function is also an object; you can assign properties to it.
function add() {
  if (add.value === undefined) add.value = 0;
  return ++add.value;
}

console.log(add());
console.log(add());

Create a local scope

var add = (function() {
  var value = 0;
  return function() {
    return ++value;
  };
})();

console.log(add());
console.log(add());

Use the global scope

function add() {
  if (window._currentValue === undefined) window._currentValue = 0;
  return ++window._currentValue;
}

console.log(add());
console.log(add());

I think that the first solution may be of particular interest to you.

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