13
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)
2

3 Answers 3

17

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanx bro, maybe i confused you, i choose the best answer
This is a best answer
8

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)

2 Comments

yeah ,maybe I dont express my meaning about this question,but you know my meaning,thank you, ceshi.apply(this,params),can work,it can provide our a dynamic method to defined a array to pass it to function, thanx u.But your first suggestion i cant get the point how can i use it
see this link for know about spread operator in javascript
2

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

1 Comment

thanx bro, maybe i confused you, i choose the best answer

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.