Create variable dynamically

-1

I have a for loop, and wanted to dynamically create a variable, so I would not retry repeating JavaScript code. I used eval , but it does not 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]);
    
asked by anonymous 08.01.2015 / 11:10

1 answer

8

You should use arrays within arrays for this, 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:

  

Do not use this version! I've added this code just so you can understand the correct syntax of what you initially tried.

No code inspires a code of these in use. It works, but the array exists to be used. This is gambiarra, and it is a 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>';
    
08.01.2015 / 11:26