所有你知道的arguments是一个特殊的对象,它包含传递给函数的所有参数.
只要它不是一个数组 - 你就不能使用类似的东西arguments.slice(1).
那么问题 - 如何切割除第一个元素之外的所有元素arguments?
UPD:
似乎没有办法没有将它转换为数组
var args = Array.prototype.slice.call(arguments);
Run Code Online (Sandbox Code Playgroud)
如果有人发布另一个解决方案,那将是很好的,如果没有 - 我将检查第一个上面的行作为答案.
nnn*_*nnn 131
问:除了第一个元素之外,如何切割所有内容arguments?
以下将返回一个包含除第一个以外的所有参数的数组:
var slicedArgs = Array.prototype.slice.call(arguments, 1);
Run Code Online (Sandbox Code Playgroud)
您不必先转换arguments为数组,只需一步即可完成.
Umu*_*göz 13
插入数组函数实际上并不是必需的.
使用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");
Run Code Online (Sandbox Code Playgroud)
...休息
Pau*_*nia 11
您可以通过程序性地遍历参数对象来"切片而不切片":
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]
Run Code Online (Sandbox Code Playgroud)
blu*_*bie 11
来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments:
您不应该对参数进行切片,因为它会阻止JavaScript引擎中的优化(例如V8).相反,尝试通过遍历arguments对象来构造一个新数组.
所以保罗罗西亚娜的答案是正确的