从 JavaScript 中的参数中删除参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19903841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing an argument from arguments in JavaScript
提问by at.
I wanted to have an optional boolean
parameter to a function call:
我想有boolean
一个函数调用的可选参数:
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 withoutthe 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:
我希望函数的其余部分只看到没有可选参数的arguments
数组。我意识到的第一件事是数组不是数组!它似乎是一个具有 0、1、2 等属性的标准。所以我不能这样做:boolean
arguments
Object
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?
我收到一个shift()
不存在的错误。那么有没有一种简单的方法可以从arguments
对象的开头删除参数?
回答by Arun P Johny
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()
arguments
不是一个数组,它是一个类似对象的数组。您可以arguments
通过访问 the来调用数组函数,Array.prototype
然后通过argument
使用.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);
回答by Clyde Lobo
As Arun pointed out arguments
is not an array
正如阿伦指出arguments
的不是一个数组
You will have to convert in into an array
你将不得不转换成一个数组
var optionalParameter = [].shift.apply(arguments);
var optionalParameter = [].shift.apply(arguments);
回答by Denys Séguret
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
这并不花哨,但在没有副作用的情况下删除第一个参数的最佳解决方案(不以附加参数结尾shift
)可能是
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