wwwanaya
wwwanaya

Reputation: 137

JavaScript, array as a parameter

How you can make this more efficient, imagine a method that you don't know how much parameters you'll need.

For example a simple ajax insert, but you don't know how much inputs has the html... so then you need to send for example 4 will be like this one:

function insert_these(data1, data2, data3, data4){
     $.post( 'test.php', { dat1: data1, dat2: data2, dat3: data3, dat4: data4 );
};

But, if you want more than 4 inputs?

How you can make a function with a parameters as a array, something like this:

inputs = new array();

function insert_these(inputs){

    //then the rest of code

    $.post(   'test.php',   for (var i = 0; i < inputs.lenght; i++){
    dat+i: inputs+i,   }; );

};

Upvotes: 2

Views: 103

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382504

This is called a variadic function and it's easy to build in JavaScript : There's an arguments pseudo-array already available in your function.

Simply iterate over it just as you do over an array and build your object :

function insert_these(){
    var obj = {};
    for (var i=0; i<arguments.length; i++) obj['dat'+(i+1)] = arguments[i];
    $.post('test.php', obj);
}

Upvotes: 2

Mihai Matei
Mihai Matei

Reputation: 24276

You can simply use an object like:

var params = {
  data1: 'data1',
  data2: 'data2'
}

insert(params);

function insert(parameters) {
   // other stuff here
   $.post('test.php', parameters);
   // other stuff here
}

Upvotes: 2

Related Questions