简体   繁体   中英

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?

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.

for循环应该循环到data.length ,而不是header.length

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM