Pass all the values from an array into a function as parameters

前端 未结 4 890
别那么骄傲
别那么骄傲 2021-02-12 20:56

I have an array of values:

[\'a\', \'b\', \'c\', \'d\']

and I need to pass these as parameters to a function:

window.myFunction         


        
相关标签:
4条回答
  • 2021-02-12 21:14

    Try

    window.myFunction.apply(window, ['a', 'b', 'c', 'd']);
    
    0 讨论(0)
  • 2021-02-12 21:21

    In ES6 you can use spread syntax.

    As from Docs:

    Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

    Your syntax will be:

    var array = ['a', 'b', 'c', 'd'];
    myFunction(...array);
    

    Demo:

    var array = ['a', 'b', 'c', 'd'];
    myFunction(...array);
    
    function myFunction(p1, p2, p3, p4) {
      console.log(p1, p2, p3, p4);
    }

    0 讨论(0)
  • 2021-02-12 21:24

    Array.prototype.map()

    var arr = ['a','b','c'];
    
    function echo(x){ 
      console.log(x)
    }
    
    function go(){
      arr.map(echo);
    }
    <button onclick="go()">Test</button>

    0 讨论(0)
  • 2021-02-12 21:25

    Use the .apply method of the Function object.

    window.myFunction.apply(window, ['a','b','c','d']);
    

    The .apply method invokes the function you're calling, but lets you set the function's this value (the first argument) and lets you set its arguments using an Array (the second argument).

    So here we kept window as the this value, and we're passing the Array as the individual arguments. The Array members will be distributed as though they were passed as individual arguments, so it's as if you had done this:

    window.myFunction('a','b','c','d');
    
    0 讨论(0)
提交回复
热议问题