Passing an array as a function parameter in JavaScript

前端 未结 10 2148
-上瘾入骨i
-上瘾入骨i 2020-11-22 10:35

I\'d like to call a function using an array as parameters:

const x = [\'p0\', \'p1\', \'p2\'];
call_me(x[0], x[1], x[2]); // I don\'t like it

function call_         


        
相关标签:
10条回答
  • 2020-11-22 10:58

    you can use spread operator in a more basic form

    [].concat(...array)
    

    in the case of functions that return arrays but are expected to pass as arguments

    Example:

    function expectArguments(...args){
      return [].concat(...args);
    }
    
    JSON.stringify(expectArguments(1,2,3)) === JSON.stringify(expectArguments([1,2,3]))
    
    
    0 讨论(0)
  • 2020-11-22 11:02

    Note this

    function FollowMouse() {
        for(var i=0; i< arguments.length; i++) {
            arguments[i].style.top = event.clientY+"px";
            arguments[i].style.left = event.clientX+"px";
        }
    
    };
    

    //---------------------------

    html page

    <body onmousemove="FollowMouse(d1,d2,d3)">
    
    <p><div id="d1" style="position: absolute;">Follow1</div></p>
    <div id="d2" style="position: absolute;"><p>Follow2</p></div>
    <div id="d3" style="position: absolute;"><p>Follow3</p></div>
    
    
    </body>
    

    can call function with any Args

    <body onmousemove="FollowMouse(d1,d2)">
    

    or

    <body onmousemove="FollowMouse(d1)">
    
    0 讨论(0)
  • 2020-11-22 11:12

    Function arguments may also be Arrays:

    function foo([a,b,c], d){
      console.log(a,b,c,d);
    }
    
    foo([1,2,3], 4)

    of-course one can also use spread:

    function foo(a, b, c, d){
      console.log(a, b, c, d);
    }
    
    foo(...[1, 2, 3], 4)

    0 讨论(0)
  • 2020-11-22 11:13

    As @KaptajnKold had answered

    var x = [ 'p0', 'p1', 'p2' ];
    call_me.apply(this, x);
    

    And you don't need to define every parameters for call_me function either. You can just use arguments

    function call_me () {
        // arguments is a array consisting of params.
        // arguments[0] == 'p0',
        // arguments[1] == 'p1',
        // arguments[2] == 'p2'
    }
    
    0 讨论(0)
提交回复
热议问题