您所知道的arguments
是一个特殊的对象,它包含传递给函数的所有参数。
只要它不是数组,就不能使用类似arguments.slice(1)
的东西。
那么问题来了——如何从arguments
中分割除第一个元素之外的所有元素?
UPD:
似乎没有办法不将其转换为具有的阵列
var args = Array.prototype.slice.call(arguments);
如果有人发布另一个解决方案,那就太好了,如果没有,我会用上面的行来检查第一个。
Q。如何从arguments
中分割除第一个元素之外的所有元素
以下将返回一个数组,该数组包含除第一个以外的所有参数:
var slicedArgs = Array.prototype.slice.call(arguments, 1);
您不必首先将arguments
转换为数组,只需一步即可完成所有操作。
实际上不需要使用数组函数
使用rest参数语法...rest
更简洁、更方便。
示例
function argumentTest(first, ...rest) {
console.log("First arg:" + first);
// loop through the rest of the parameters
for (let arg of rest) {
console.log("- " + arg);
}
}
// call your function with any number of arguments
argumentTest("first arg", "#2", "more arguments", "this is not an argument but a contradiction");
。。。休息
- 参见Fiddle示例
- 请参阅MDN文档页面
来源https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments:
您不应该对参数进行切片,因为它会阻止JavaScript引擎(例如V8)。相反,尝试构建一个数组。
所以Paul Rosiana上面的答案是正确的
这可以是一种方式:
var args = Array.from(arguments).slice(1);
您可以通过程序化地遍历arguments对象来"切片而不切片":
function fun() {
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
return args;
}
fun(1, 2, 3, 4, 5); //=> [2, 3, 4, 5]
您可以使用方法[].slice.call(arguments, 1)
[].slice将返回slice函数对象,您可以调用它,因为arguments
和1
是参数
您可以使用。。。rest在函数中用于分离第一个和其余参数:
function foo(arr) {
const [first, ...rest] = arguments;
console.log(`first = ${first}`);
console.log(`rest = ${rest}`);
}
//Then calling the function with 3 arguments:
foo(1,2,3)
您也可以使用
function arg(myArr) {
let arg = Object.values(arguments).slice(2, 4);
console.log(arg);
return arg;
};
arg([1, 2, 3], 4, [5,6], 7)
请参阅此处以供参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
Arguments
类型是可迭代的,因此使用ES6 (ES2015)
扩展...
运算符,然后使用Array.slice([start], [end])
方法,例如
function omitFirstAndLastArgument(value) {
const args = arguments.length > 2 ? [...arguments].slice(1, -1) : [];
return args;
}
omitFirstAndLastArgument(1, 2, 3, 4, 5, 6); // [2, 3, 4, 5]