首页 > 解决方案 > 无法在 JavaScript 中的可变长度参数数组上运行函数

问题描述

我正在尝试对我的参数执行一个函数,该函数是可变长度的。我似乎无法在我的参数数组上运行任何函数,包括排序。

function findKeyFromNotes()
    {
         var notes = arguments.slice(); 
         return notes;  
    }

我收到此错误:

TypeError: arguments.slice is not a function

谢谢,纳库尔

标签: javascriptfunctionarguments

解决方案


在现代 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
}

推荐阅读