Dynamically create variable

Asked

Viewed 199 times

-1

I have a cycle for, and wanted to create a variable dynamically, not to repeat code again in Javascript. I used the eval, but it doesn’t work. Example:

for (var y = 1; y <= 2; y++) {
    eval('var max_arr' + y + ' = Math.max.apply(Math, this["arr_valeur" + y];');
}

or this:

var max_arr+y = Math.max.apply(Math, this["arr_valeur"+y]);
  • 1

    It’s not easier to use one array? And you’d better add to the question the result you want to get, not just how you’re trying to solve it. And what would be the advantage of applying max to one item?

  • how can I use the array? The result I want to get is the maximum value of another array.

  • The loop is to use the variable 2 times with its different name. Or max_arr1 and max_arr2.

  • I added an example to facilitate understanding.

  • I definitely cannot understand why so many votes against the question...

1 answer

8


You must use arrays inside arrays for this, and not eval.

Syntax:

for(var y = 1; y <= 2; y++ ) {
   max_arr[y] = Math.max.apply( null, arr_valeur[y] );
}


Example:

var arr_valeur = [];
var plus_grand = [];

arr_valeur[1] = [ 112,   1, 389 ];
arr_valeur[2] = [  44,  42,  30 ];

for ( var y = 1; y <= 2; y++) {
  plus_grand[y] = Math.max.apply(null, arr_valeur[y]);
}

document.body.innerHTML += plus_grand[1] + '<br>';
document.body.innerHTML += plus_grand[2] + '<br>';


Using Eval:

Don’t use this version! I added this code just so you understand the correct syntax of what you tried to do initially.

It does not inspire any confidence a code like this in use. It works, but the array exists to be used. This here is gambiarra, and is sign of insufficient knowledge of the language:

var arr_valeur1 = [ 112,   1, 389 ];
var arr_valeur2 = [  44,  42,  30 ];

for ( var y = 1; y <= 2; y++) {
   eval( 'var max_arr' + y + ' = Math.max.apply(null, arr_valeur' + y + ');' );
}

document.body.innerHTML += max_arr1 + '<br>';
document.body.innerHTML += max_arr2 + '<br>';

Browser other questions tagged

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