从 JavaScript 中的参数中删除参数 [英] Removing an argument from arguments in JavaScript
问题描述
我想要一个可选的 boolean
参数来调用函数:
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
}
我希望函数的其余部分只看到 arguments
数组没有可选的 boolean
参数.我意识到的第一件事是 arguments
数组不是数组!它似乎是一个标准的 Object
属性为 0、1、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();
我收到一个错误,指出 shift()
不存在.那么有没有一种简单的方法可以从 arguments
对象的开头删除一个参数?
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?
推荐答案
arguments
不是数组,而是类似对象的数组.您可以通过访问 Array.prototype
然后通过使用 .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);
演示
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);
演示
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);
这篇关于从 JavaScript 中的参数中删除参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!