Passing an array as a function parameter in JavaScript

前端 未结 10 2147
-上瘾入骨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:50

    Why don't you pass the entire array and process it as needed inside the function?

    var x = [ 'p0', 'p1', 'p2' ]; 
    call_me(x);
    
    function call_me(params) {
      for (i=0; i<params.length; i++) {
        alert(params[i])
      }
    }
    
    0 讨论(0)
  • 2020-11-22 10:50

    Assuming that call_me is a global function, so you don't expect this to be set.

    var x = ['p0', 'p1', 'p2'];
    call_me.apply(null, x);
    
    0 讨论(0)
  • 2020-11-22 10:50

    While using spread operator we must note that it must be the last or only parameter passed. Else it will fail.

    function callMe(...arr){ //valid arguments
        alert(arr);
    }
    
    function callMe(name, ...arr){ //valid arguments
        alert(arr);
    }
    
    function callMe(...arr, name){ //invalid arguments
        alert(arr);
    }
    

    If you need to pass an array as the starting argument you can do:

    function callMe(arr, name){
        let newArr = [...arr];
        alert(newArr);
    }
    
    0 讨论(0)
  • 2020-11-22 10:52
    const args = ['p0', 'p1', 'p2'];
    call_me.apply(this, args);
    

    See MDN docs for Function.prototype.apply().


    If the environment supports ECMAScript 6, you can use a spread argument instead:

    call_me(...args);
    
    0 讨论(0)
  • 2020-11-22 10:54

    The answer was already given, but I just want to give my piece of cake. What you want to achieve is called method borrowing in the context of JS, that when we take a method from an object and call it in the context of another object. It is quite common to take array methods and apply them to arguments. Let me give you an example.

    So we have "super" hashing function which takes two numbers as an argument and returns "super safe" hashed string:

    function hash() {
      return arguments[0]+','+arguments[1];
    }
    
    hash(1,2); // "1,2" whoaa
    

    So far so good, but we have little problem with the above approach, it is constrained, only works with two numbers, that is not dynamic, let's make it work with any number and plus you do not have to pass an array (you can if you still insist). Ok, Enough talk, Let's fight!

    The natural solution would be to use arr.join method:

    function hash() {
      return arguments.join();
    }
    
    hash(1,2,4,..); //  Error: arguments.join is not a function
    

    Oh, man. Unfortunately, that won’t work. Because we are calling hash(arguments) and arguments object is both iterable and array-like, but not a real array. How about the below approach?

    function hash() {
      return [].join.call(arguments);
    }
    
    hash(1,2,3,4); // "1,2,3,4" whoaa
    

    The trick is called method borrowing.

    We borrow a join method from a regular array [].join. And use [].join.call to run it in the context of arguments.

    Why does it work?

    That’s because the internal algorithm of the native method arr.join(glue) is very simple.

    Taken from the specification almost “as-is”:

    Let glue be the first argument or, if no arguments, then a comma ",".
    Let result be an empty string.
    Append this[0] to result.
    Append glue and this[1].
    Append glue and this[2].
    …Do so until this.length items are glued.
    Return result.
    

    So, technically it takes this and joins this[0], this[1] …etc together. It’s intentionally written in a way that allows any array-like this (not a coincidence, many methods follow this practice). That’s why it also works with this=arguments.

    0 讨论(0)
  • 2020-11-22 10:58

    In ES6 standard there is a new spread operator ... which does exactly that.

    call_me(...x)
    

    It is supported by all major browsers except for IE.

    The spread operator can do many other useful things, and the linked documentation does a really good job at showing that.

    0 讨论(0)
提交回复
热议问题