How to save a function’s parameters to a variable?

Asked

Viewed 340 times

3

I want to perform this function coord(343,5,6,2,86528,875433, longitude, latitude, 'COORDENADAS');

But I wanted to save the parameters to run the function later. How to save?

I tried to var x = 343,5,6,2,86528,875433, longitude, latitude, 'COORDENADAS' but makes a mistake.

  • What do you mean you want to call it again? You want to run it again using the same parameters?

  • @Kaduamaral Yes, updating one or two parameters but using the same base.

2 answers

3


You can access the object arguments of function:

var args; // Variável no escopo global para salvar os parâmetros
function MinhaFuncao(x, y, z, w, k, j){
    args = arguments; // Salva os parâmetros passado
    console.log(arguments);
    document.getElementById('log').innerHTML = arguments[1];
}
//; Executa função primeira vez
MinhaFuncao(1, 'arroz', 3.14, 'macarrão', true, 'joão', 'picolé', 'maracujá');

// Alterando o terceiro argumento
args[2] = 'Feijão';

// Pode chama-la novamente usando o apply:
if (args != undefined)
   MinhaFuncao.apply(this, args); 
   // Primeiro parâmentro é o contexto, 
   // o segundo é o array de argumentos
<p id="log"></p>

Return of the object arguments:

Arguments[8] {
  0: 1
  1: "arroz"
  2: 3.14
  3: "macarrão"
  4: true
  5: "joão"
  6: "picolé"
  7: "maracujá"
}
  • Interesting, countering that it was not necessary to save separately and it is possible to save and edit, thanks!

  • Like arguments is a special type, I would recommend saving as array: args = Array.prototype.slice.call(arguments, 0);

  • Have any particular reason or situation that just assign it directly would be a @bfavaretto problem?

  • It is usually not expected to find an Arguments type object outside of a function.

2

Would that be:

var p1 = 343, p2 = 5, p3 = 6, p4 = 2, p5 = 86528, p6 = 875433, 
    p7 = longitude, p8 = latitude, p9 = 'COORDENADAS';

I put in the Github for future reference.

Note that you have 9 parameters there, need to save in 9 variables. Could use the array also, but I think it’s even better in this case that there are nine variables. The only thing that should change in relation to what I did is to give more meaningful names to the variables, indicating what each parameter is.

You may not think it’s a good solution, but I don’t see a better one, although there are other creative ones. I don’t really know why you need this, maybe you don’t even have this need. It doesn’t make much sense to do this. It’s possible that the whole design of the application is wrong.

  • Yes, you did, I understand. But it is a request that goes to the server and was rejected, that is I need to resend it with the same parameters but updating some so that it is not rejected again, I do not see a design problem, if you have a better solution.. Thanks anyway!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.