NC LI
NC LI

Reputation: 179

how can I pass multiple parameters in javascript function

function ceshi(test,lyj,param1,parm2){
    console.log(arguments)
}
var params = [2,3];
ceshi(eval('2,3'));

if params is not uncertain, how can I pass params through a method.I want to realize below result.

the function has fixed params,but I have more than one function like

ceshi(1,2,123)
ceshi(1,3123)
ceshi('xxx','ssssss','12313',12)

Upvotes: 13

Views: 58210

Answers (3)

Koushik Chatterjee
Koushik Chatterjee

Reputation: 4175

To call a function, by passing arguments from an array

  1. Either use spread operator ceshi(...params)
  2. Use apply function to invoke it ceshi.apply(<Context>, params)

Upvotes: 8

javier__nogales
javier__nogales

Reputation: 31

You can set params with object, for example:

        function ceshi(options)
        { 
            var param1= options.param1 || "dafaultValue1";
            var param2= options.param2 || "defaultValue2";
            console.log(param1);
            console.log(param2);
        }

        ceshi({param1: "value1", param2:"value2"});
        ceshi({param2:"value2"});
        ceshi({param1: "value1"});

Upvotes: 2

AJ H
AJ H

Reputation: 757

You can use spread operator in ECMAScript 6 like this:

function ceshi(...params) {
  console.log(params[0]);
  console.log(params[1]);
  console.log(params[2]);
}

Or use the "arguments" variable within a function like this:

function ceshi() {
  console.log(arguments[0]);
  console.log(arguments[1]);
  console.log(arguments[2]);
}

To understand further deeper, I will highly recommend you to read this material.

Upvotes: 17

Related Questions