How to generate incremental variables with Javascript?

3

I would like to know how to generate incremental variables, for example:

var camada = 0
for (i=0; i=20;i++){
    var "camada" + i + 1 = 12
}

I know that the code is not correct, but I wrote to illustrate what I would like to do, you have to automatically generate the variables layer1 , layer2 , layer3 , .. layer20 .

    
asked by anonymous 08.05.2015 / 05:31

2 answers

7

This may not be possible, if it is, it does not make up for the effort, the use of an array should be more practical.

var camadas = {};
for (var i = 0; i <= 20; ++i) {
    camadas["camada" + i] = 'Hello World ' + i;
}

To retrieve a value, simply specify the key camadaN , where N is the number in a range between 0 and 20 :

alert(camadas.camada5); // Hello World 5
//alert(camadas["camada5"]); // Sintaxe alternativa

To change the value of a key, do the following:

camadas.camada5 = "foo";
camadas.camada6 = "bar";
// Sintaxe alternativa
//camadas["camada5"] = "foo"; 
//camadas["camada6"] = "bar";

Exemplo

Update

According to this comment:

  

I am creating a web page, to caucular tensions on the ground, each   Soil layer has Height and Weight . I created an input that the   person types the number of layers. If the user types 5 for   example, 10 inputs will be generated, 5 for height and 5 for   Specific ... So for each layer I have to generate the variables   to do the calculations .... That's why I need to generate the   each layer ... I created them as objects, in the case a new layer I   I would only instantiate it, but I still have the same problem.

Use an array of arrays . Assuming it is necessary that each layer has specific height and weight, just do the following:

var camadas = {};
for (var i = 0; i <= 20; ++i) {
    camadas["camada" + i] = { 'altura': 'altura' + i,
                              'peso': 'peso' + i};
}

To retrieve the weight and height of a layer, simply specify the camadaN and the keys, in this case, altura and peso . Here's an example:

alert(camadas.camada1.altura); // Valor da altura da camada1
alert(camadas.camada20.peso);  // Valor do peso da camada20

Exemplo

    
08.05.2015 / 05:40
4

Some ways follow below.

1) A global scope variable:

window['nomeDaVariavel'] = 1;
console.log(window.nomeDaVariavel); // Irá exibir o valor '1' no Console.

2) Compilation via eval:

eval("var variavel = 1");
console.log(variavel); // Irá exibir o valor '1' no Console.

But my suggestion would be to use arrays ( variavel[1] , variavel[2] , etc.) instead of dynamically declared variables. This makes handling the collection much easier.

The snippet below, in AngularJS, demonstrates this technique: The $scope.camadas property is initialized as an array (via $scope.camadas = [] ). Note after this the use of push (to add a new member), splice (to remove a member) and forEach (which allows iterating over all members of the array):

$myApp = angular.module('myApp',[]);

camadasCtrl = function($scope) {
  
  $scope.camadas = [];
  //        ^ inicializando o array
  $scope.peso = 0;

  $scope.addCamada = function() {
    $scope.camadas.push( {peso: $scope.peso } );
    //               ^ Adiciona um membro ao array
    
    calcTotal();

    
    $scope.peso = parseInt(Math.random() * 1000000) / 100;
  }
  $scope.delCamada = function(index) {
    $scope.camadas.splice(index, 1);
    //               ^ Remove um membro do array
    
    calcTotal();
  }
  
  var calcTotal = function() {
    
    var total = 0;
    
    $scope.camadas.forEach(function(item) {
    //                ^ Para cada membro do arry, o código a seguir é executado
        total += item.peso;
    });
    
    $scope.pesoTotal = total;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app='myApp'><divng-controller='camadasCtrl'>Peso:<inputtype='text'ng-model='peso'><buttonng-click='addCamada()'>AdicionarCamada{{camadas.length}}</button><divng-repeat='camadaincamadas'><buttonng-click='delCamada($index)'>Remover</button>Camada{{$index}}:{{camada.peso}}Kg</div>PesoTotal:{{pesoTotal}}</div></div>

Theresultisasfollows:

    
08.05.2015 / 06:39