[英]Can't run function on variable-length argument array in JavaScript
I am trying to perform a function on my arguments, which is variable length.我正在尝试在我的 arguments 上执行 function,它是可变长度的。 I can't seem to run any function on my arguments array, including sort.
我似乎无法在我的 arguments 数组上运行任何 function,包括排序。
function findKeyFromNotes()
{
var notes = arguments.slice();
return notes;
}
I am getting this error:我收到此错误:
TypeError: arguments.slice is not a function
Thanks, Nakul谢谢,纳库尔
In modern JavaScript, you can use the spread syntax to collect all arguments into a single array value:在现代 JavaScript 中,您可以使用扩展语法将所有 arguments 收集到单个数组值中:
function findKeyFromNotes(... notes) {
// notes will be an array
}
In "traditional" JavaScript the best thing to do would be:在“传统” JavaScript 中,最好的做法是:
function findKeyFromNotes() {
var notes = [];
for (var i = 0; i < arguments.length; ++i) notes[i] = arguments[i];
// now notes is a plain array
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.