从JavaScript中移除参数的参数 [英] Removing an argument from arguments in JavaScript

查看:150
本文介绍了从JavaScript中移除参数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个可选的布尔参数函数调用:

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
}

我要的函数的其余部分,只看到参数阵列的可选布尔参数。我意识到的第一件事就是参数 array不是一个数组中!这似乎是一个标准的对象带,1 0性能,2等,所以我不能做的:

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?

推荐答案

参数不是一个数组,它就像对象的数组。您可以拨打参数通过访问<一个阵列功能href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype\">Array.prototype然后使用传递参数作为其执行上下文<一个调用它href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply\">.apply()

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()

尝试

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

演示:小提琴

另外,我在某些地方看到的版本是

another version I've seen in some places is

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

演示:小提琴

这篇关于从JavaScript中移除参数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆