Javascript add extra argument

后端 未结 11 1037
暖寄归人
暖寄归人 2021-02-06 22:02

Lets take a look at this code:

var mainFunction = function() {
  altFunction.apply(null, arguments);
}

The arguments that are passed to \"mainF

相关标签:
11条回答
  • 2021-02-06 22:18

    One liner to add additional argument(s) and return the new array:

    [].slice.call(arguments).concat(['new value']));
    
    0 讨论(0)
  • 2021-02-06 22:19

    The arguments "array" isn't an array (it's a design bug in JavaScript, according to Crockford), so you can't do that. You can turn it into an array, though:

    var mainFunction = function() {
      var mainArguments = Array.prototype.slice.call(arguments);
      mainArguments.push('extra data');
    
      altFunction.apply(null, mainArguments);
    }
    
    0 讨论(0)
  • 2021-02-06 22:25

    For those who like me was looking for a way to add an argument that is optional and may be not the only omitted one (myFunc = function(reqiured,optional_1,optional_2,targetOptional) with the call like myFunc(justThisOne)), this can be done as follows:

    // first we make sure arguments is long enough
    // argumentPosition is supposed to be 1,2,3... (4 in the example above)
    while(arguments.length < argumentPosition)
        [].push.call(arguments,undefined);
    // next we assign it
    arguments[argumentPosition-1] = arguments[argumentPosition-1] || defaultValue;
    
    0 讨论(0)
  • 2021-02-06 22:26
    var mainFunction = function() {
        var args = [].slice.call( arguments ); //Convert to array
        args.push( "extra data");
        return altFunction.apply( this, args );
    }
    
    0 讨论(0)
  • 2021-02-06 22:29

    Update 2016: You must convert the arguments to an array before adding the element. In addition to the slice method mentioned in many posts:

    var args = Array.prototype.slice.call(arguments);
    

    You can also use the Array.from() method or the spread operator to convert arguments to a real Array:

    var args = Array.from(arguments);
    

    or

    var args = [...arguments];
    

    The above may not be optimized by your javascript engine, it has been suggested by the MDN the following may be optimized:

    var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

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