javascript - 无法在 JavaScript 中的可变长度参数数组上运行函数
问题描述
我正在尝试对我的参数执行一个函数,该函数是可变长度的。我似乎无法在我的参数数组上运行任何函数,包括排序。
function findKeyFromNotes()
{
var notes = arguments.slice();
return notes;
}
我收到此错误:
TypeError: arguments.slice is not a function
谢谢,纳库尔
解决方案
在现代 JavaScript 中,您可以使用扩展语法将所有参数收集到单个数组值中:
function findKeyFromNotes(... notes) {
// notes will be an array
}
在“传统” JavaScript 中,最好的做法是:
function findKeyFromNotes() {
var notes = [];
for (var i = 0; i < arguments.length; ++i) notes[i] = arguments[i];
// now notes is a plain array
}
推荐阅读
- android - xxhdpi 文本到 textView textSize
- javascript - 从 DOM 片段中移除特定颜色
- postman - 无法将数组设置为环境变量 - 邮递员测试
- c# - 如何将连接的客户端列表从服务器发送到客户端,区分常规消息?
- javascript - 计算轮盘赌赢家的数学
- c# - 使用 C# 确定哪个鼠标在多个鼠标中触发 Click 事件?
- python-3.x - Cython 编译器指令 language_level 不受尊重
- vba - 在 vba 中使用 getElementsByTagName 返回运行时错误 91 对象变量或未设置块变量
- html - 在带有过渡的悬停更改动画上
- c# - 使用 MVVM 模式将列表传递给类