Removing an argument from arguments in JavaScript

*爱你&永不变心* 提交于 2019-12-22 04:09:32

问题


I wanted to have an optional boolean parameter to a function call:

function test() {
  if (typeof(arguments[0]) === 'boolean') {
    // do some stuff
  }
  // rest of function
}

I want the rest of the function to only see the arguments array without the optional boolean parameter. First thing I realized is the arguments array isn't an array! It seems to be a standard Object with properties of 0, 1, 2, etc. So I couldn't do:

function test() {
  if (typeof(arguments[0]) === 'boolean') {
    var optionalParameter = arguments.shift();

I get an error that shift() doesn't exist. So is there an easy way to remove an argument from the beginning of an arguments object?


回答1:


arguments is not an array, it is an array like object. You can call the array function in arguments by accessing the Array.prototype and then invoke it by passing the argument as its execution context using .apply()

Try

var optionalParameter = Array.prototype.shift.apply(arguments);

Demo

function test() {
    var optionalParameter;
    if (typeof (arguments[0]) === 'boolean') {
        optionalParameter = Array.prototype.shift.apply(arguments);
    }
    console.log(optionalParameter, arguments)
}
test(1, 2, 3);
test(false, 1, 2, 3);

another version I've seen in some places is

var optionalParameter = [].shift.apply(arguments);

Demo

function test() {
    var optionalParameter;
    if (typeof (arguments[0]) === 'boolean') {
        optionalParameter = [].shift.apply(arguments);
    }
    console.log(optionalParameter, arguments)
}
test(1, 2, 3);
test(false, 1, 2, 3);



回答2:


As Arun pointed out arguments is not an array

You will have to convert in into an array

var optionalParameter = [].shift.apply(arguments);




回答3:


It's not fancy but the best solution to remove the first argument without side effect (without ending with an additional argument as would do shift) would probably be

  for (var i=0;i<arguments.length;i++) arguments[i]=arguments[i+1];

Example :

function f(a, b, c, d) {
  for (var i=0;i<arguments.length;i++) arguments[i]=arguments[i+1];
  console.log(a,b,c,d); 
}
f(1,2,3,4); // logs 2,3,4,undefined


来源:https://stackoverflow.com/questions/19903841/removing-an-argument-from-arguments-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!