0

I have a javascript function in which I build an array. To this array I apply the shift function, so the array at the end is empty. What I need to do is to save the values of the array before it becomes empty. I tried to save the values in another array but I don't undersantd why but it doesn't function ad I expect. The code is the following:

  function tableHeadersToArray(Firstheader_fields, header_fields){

        //- Put all header1 > td elements in a collection
        var row1tds = Firstheader_fields;

        //I define the variable at the beginning of my javascript code before the function
        //var header1Colspans = [];
        //var pippo = [];
        // var indice;  

        //at the first run indice will be 1     
        if(indice ==2){
           header1Colspans=pippo;           
        }else{
           indice =1;
        }

        if(indice==1){      
          for(var index=0; index<row1tds.length; index++){               
             header1Colspans.push(row1tds[index].getAttribute('colspan') || 1);
          //in this way I assign to pippo the values of header1Colspans
             pippo = header1Colspans;
          }
            indice=2;
        }

        //- Put all header2 > td elements in a collection
          var row2tds = header_fields;

        //- This is the tricky part
        //- Draw 2 arrays, one below the other on a pice of paper
        //- and place your 2 index fingers at the beginning of each one.
        //- Your left index finger is index1, and your right is index2.
        //- Follow the code, and each time one is incremented, move it
        //- to the right one cell.

        var colspan, index1=0, index2=0, resultingArray=[];

        //- (colspan = header1Colspans.shift()) gets the first element of the array,
        //- assigns it to var colspan and the expression has the value TRUE if the
        //- assignment was made, or FALSE if there were no more elements in the array
        while(index1 < row1tds.length && (colspan = header1Colspans.shift())){
          while(index2 < row2tds.length && colspan > 0){                   
             var Value1=row1tds[index1].textContent;
             var LenghtVal=Value1.length;

        //- Here we concatenate 'ROME' + '-' + 'CITIES' and add it to the array
        // - In case the Header1 is blank we don't concatenate the values
             if(LenghtVal > 1){                  
                 resultingArray.push(row1tds[index1].textContent + ' - ' + 
                  row2tds[index2].textContent);
              }else{                     
                 resultingArray.push(row2tds[index2].textContent);
               }
              index2++;
              colspan--;
             }
           index1++;
        }
      return resultingArray;    
    }

When I open my HTML page the function is executed so the header1Colspans at the end of the function is empty. Then when I click on a button that I have on my html table the function is executed again and the array is populated each time with the new colspan attribute (in another function i need to change the values of the colspan). The point is that in this function I want just the values of the first time the function is executed so i want take the original colspan values. For this reason I have created the array pippo, because I thought to save the values there and then to use just pippo but it doesn't work. Thanks in advance.

0

1 Answer 1

1

If you have 2 arrays in JavaScript, a and b, b = a will make b a reference to a. Example:

var a = [1, 2, 3, 4];
var b = a;

console.log(b);
// It will print [1, 2, 3, 4]

// Let's remove the last element of 'a':
a.pop();

console.log(b);
// It will print [1, 2, 3], because 'b' is a reference to 'a'

That said, you cannot clone an array like in the example. Fortunately there are alternatives, see some examples below. You need to use that line before you use the shift() in your array. I will not explain them here, but you can use the one that suits you best:

var myCopyOfTheArray = header1Colspans.slice(0);
var myCopyOfTheArray = header1Colspans.map(x => x);
var myCopyOfTheArray = header1Colspans.filter(() => true);
var myCopyOfTheArray = [...header1Colspans];
Sign up to request clarification or add additional context in comments.

5 Comments

You could also use the spread operator var myCopy = [...header1Colspans]
hi, thanks for the answer! I used the slice and it works as I expected, but just the first time the function is executed. The second time pippo which is my b becomes empty. -.-'
Hi @Dana. I noticed you did not initialize the pippo variable. Try adding var pippo; in the beginning (inside) of your function. If you do not use var (or let, or const) the variable is created in the global scope instead of the function scope. I believe this is the reason for your problem. You can find a detailed explanation here: sitepoint.com/demystifying-javascript-variable-scope-hoisting
no it is not the problem, if i add pippo inside the function each time the function is called I lost the value of pippo. The value of pippo should be set the first time and i need to mantain it each time the function is called. for this reason I initialize the variable outside the function. thanks for your help
ok i fixed the problem by using the slice each time i need to assign the values to my array. I had other parts i the code in which i continued using pippo= header1Colspans so I lost the values. Using everywhere the slice it work perfectly! Thanks again for the collaboration

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.