Rename a variable using Function /Javascript Parameters

Asked

Viewed 1,110 times

2

That’s just one example:

function myfunction(u)

e+"u" = 1
x+"u" = 1
o+"u" = 1

//ai chamando ela...

myfunction(1)

e1 = 1
x1 = 1
o1 = 1 

You could make it valid or do something like that?

  • I couldn’t understand anything. What is the purpose? The code doesn’t make sense either.

  • I think what you are looking for has to do with reflection. https://pt.wikipedia.org/wiki/Reflex%C3%A3o_(program%C3%A7%C3%A3o)

  • This code doesn’t work, it’s just an example, I want the value of the parameter to join with the variable

  • Do you want to concatenate the variable name with the argument? This is not ideal, in these cases better use array (there is the eval tb, not recommended) or other data structure, anyway, in your example you are concatenating with the string "u", not the argument u.

  • and how I would do that?

2 answers

1

Javascript has objects, based on keys and values such that I believe to be most useful for what you are trying to do. This way, it is possible to add n keys, and then recover in various ways. Based on your example:

var meuObjeto = {}

function myfunction(u) {
  meuObjeto['e'+ u] = 1;
  meuObjeto['x' + u] = 1;
  meuObjeto['o' + u] = 1;
}

myfunction(1);
console.log(meuObjeto);

0

You can use the window variable as a global scope and change the object property, it would look something like :

function myfunction(u){
  window['e'+u] = 1;
  window['x'+u] = 2;
  window['o'+u] = 3;
}

myfunction(1)
console.log(e1); //1
console.log(x1); //2
console.log(o1); //3

Browser other questions tagged

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