How to generate incremented variables with Javascript?

Asked

Viewed 298 times

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 the code is not correct, but I wrote to better illustrate what I would like to do, you have to automatically generate the variables camada1, camada2, camada3,.. camada20.

  • 3

    If these variables are global, until it is possible: just use window["camada" + (i+1)] = 12; (attention to the association of the operator +). Then you could access it, say, like x = camada4;. But as already said in the answers, this is a bad idea, even if they were not global, better to use an array even or maybe an object.

  • 1

    Can you explain what the fineness is where you need it? If you mention the final problem we can give the right solution.

  • I am creating a web page, to caucular the tensions in the soil, each layer of soil has Specific Height and Weight I created an input that the person type the amount of layers. If the user type 5 for example, 10 inputs will be generated, 5 for height and 5 for Specific Weight... So for each layer I have to generate the variables to make the calculations.... That’s why I need to generate the variables of each layer...I created them as objects, in case a new layer I would only leave it, but I still have the same problem

  • I want to make use of the following form --for (var i=0; i<20; i++) { Document.getElementById("thickening"+(i+1)). innerHTML=" "+layer(i+1). height +"m"

  • I’ll test...Thanks already bring the answer

  • Friend, you got it right, that’s what I wanted...many thanks var layers = {}; for (var i = 0; i <= 20; ++i) { layers["layer" + i] = { 'height': 'height' + i, 'weight': 'weight' + i}; }

  • @Great Jacobathias. If possible mark the reply as the one that solved, click on the below of the score. Also vote positively on the answers that helped you!

Show 2 more comments

2 answers

7


That maybe it is not possible, if it is, not worth the effort, the use of a array should be more practical.

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

To recover a value, just 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:

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

Exemplo

Updating

As per this comment:

I’m creating a web page, to caucular the tensions in the ground, each soil layer has Height and Heaviness Specific. I created a input that the person type the amount of layers. If user type 5 per example, 10 inputs will be generated, 5 for height and 5 for weight Specific... So for each layer I have to generate the variables to make the calculations.... That’s why I need to generate the variables of each layer...I created them as objects, in this case a new layer I I would only instantiate her, but I still have the same problem.

Use a 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 regain the weight and height of a layer, simply specify the camadaN and the keys in case, altura and peso. Take an example:

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

Exemplo

  • 2

    I think it would be better if the layers were indexed starting at 0.

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.

However my suggestion would be to use arrays (variavel[1], variavel[2], etc.) rather than dynamically declared variables. This makes collection manipulation much easier.

The snippet below, in Angularjs, demonstrates this technique: The property $scope.camadas is initialized as a 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 iteration on 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>

    <div ng-app='myApp'>

      <div ng-controller='camadasCtrl'>
        Peso: <input type='text' ng-model='peso'> <button ng-click='addCamada()'> Adicionar Camada {{ camadas.length }} </button>

        <div ng-repeat='camada in camadas'>
          <button ng-click='delCamada($index)'> Remover</button> Camada {{$index}} : {{ camada.peso }} Kg           
        </div>
        
        Peso Total: {{ pesoTotal }}
        
        
      </div>
    </div>

The result is as follows:

inserir a descrição da imagem aqui

  • I understood your intention with the second example, but there it has neither variables nor scope. These are properties of objects.

  • @bfavaretto This is because according to ECMA5, the global primitive and global Variableobject objects (the first responsible for properties, and the second for variables) are the same. According to the same specification, what differentiates one from the other is the scope; examples 1 and 2 use the same principle. Note that ECMA5 declares what is a property, but not a variable: http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.26

  • I know, this is possible if the variables are global. But your example 2 speaks in "local scope". Objects that hold the local scope are not exposed to language (and even expose the object holding the global scope is optional). The only way to create variables dynamically in a local scope is with eval - and how your answer shows this can usually be avoided using arrays or objects, which also makes the code clearer and more organized.

  • 1

    @bfavaretto correct, thank you - I will remove example.

Browser other questions tagged

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