Reputation: 179
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
Reputation: 4175
To call a function, by passing arguments from an array
ceshi(...params)
apply
function to invoke it ceshi.apply(<Context>, params)
Upvotes: 8
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
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