2

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,   }; );

};

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Notice that the function argument list data1, data2, data3, data4 is unused and not needed. You can change the function definition to function insert_these() { ... }.
@MattiasBuelens You're right, that was just a unfixed copy-paste
2

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
}

Comments

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.