codeBarer
codeBarer

Reputation: 2388

passing a 2d array into a function using JavaScript

I'm trying to pass a two dimensional array into a JavaScript function but I only get the first element of the two dimensional array. Below is an excerpt of my code:

header = [['Objective','summary'],['Status','txtHealth']];

...


function setTableHeader(data){
    console.log(data);
    var table = document.getElementById('tblData').tHead.insertRow(0);

    for (var i = 0; i < header.length; i++)
        table.insertCell(i).innerHTML = data[i];

};


/*calling the function*/
setTableHeader.apply(this,header);

The console log shows only ['Objective','summary'], is it because the function gets passed only the pointer to the memory location of the first memory block of the array?

I'm new to webdev and I'm also curious if I should be using global variables whenever I can rather than local variables?

Upvotes: 1

Views: 2987

Answers (3)

ledzep2
ledzep2

Reputation: 841

Function arguments in javascript are passed either as value or as reference.

Primitive types, like int, string are passed as value.

Object types, like array, object are passed as reference.

In your case, apply is the devil here. apply takes an array of arguments and apply them to the function as positional arguments, which means the array of header got expanded. So if you want to get your header right, do it like this:

setTableHeader.apply(this,[header]);

Upvotes: 0

PSL
PSL

Reputation: 123739

First issue is you are using apply which takes argument as array So you should do.

setTableHeader.apply(this,[header]);

otherwise your header array's each row will go in as its own argument to the function. So your data will be just ['Objective','summary']

But you can just invoke the function as is here:

  setTableHeader(header);

Also if you have header defined as global you don't need to pass the data through to the function as argument. Hoewever your for loop checks for the length of header array instead of the passed in data length. Which mismatches here due to the apply issue.

Upvotes: 3

ffflabs
ffflabs

Reputation: 17481

The for loop should be looping until data.length, not header.length.

Upvotes: 1

Related Questions