jrob11
jrob11

Reputation: 315

for loop to assign values to multiple variables

I'm wondering if there is a way to create a for loop that will assign values to a variables that would look something like this: ('preview' is a variable assigned earlier in my code that provides access to the spreadsheet).

     <? 
          var i;
          for (i=0;i<20;i++){
            var values = preview.getRange('B5:B24').getValues(); //list of values to be assigned to variables
            var bills = //code that creates a variable "Bill" + i as array (result: "Bill1", "Bill2", "Bill3", etc)
            for (let bill of bills){ //my attempt at assigning values to bills
               bill == values[i] //"bill" here would be the variable that refers to "Bill1", "Bill2", "Bill3", etc). values would refer to my array, and [i] would be for the corresponding order

     ?>

Here is a small example: Let's just say I'm using 3 bills, and the values will be "$100", "$75", and "$240" respectively. The result of the function would do the equivalent of typing this:

            var Bill1 = 100;
            var Bill2 = 75;
            var Bill3 = 240;

These variables would then later be called upon as <?= Bill1 ?>

EDIT (CLARITY): The first challenge for me is to create an array of all the bills, something like this:

  ```
     var i;
     var bills = { //attempt to create array of all results ("Bill1", etc)
     for (i=0;i<20;i++){ //THIS IS THE PART MOSTLY IN QUESTION
      "Bill" + i + 1 //to result in "Bill1", "Bill2", etc
     };}


     //then loop through bill of bills to assign values[i]
     for (let bill of bills) {
       bill == value[i];
       i++;
     }

Upvotes: 0

Views: 106

Answers (1)

TheMaster
TheMaster

Reputation: 50799

A array is a collection of values and is the recommended way to store multiple related values instead of creating a variable name for each value.

These variables would then later be called upon as <?= Bill1 ?>

It is also possible to call each value in a array as:

<?= Bill[1]?>

To list all values,

<? 
        const values = preview.getRange('B5:B24').getValues(); //list of values to be assigned to variabl
        for (let [bill] of values){ 
?>
         <ul><?=bill?></ul>

<?      }     ?>

References:

Upvotes: 2

Related Questions