简体   繁体   中英

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. I can't seem to run any function on my arguments array, including sort.

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:

function findKeyFromNotes(... notes) {
  // notes will be an array
}

In "traditional" JavaScript the best thing to do would be:

function findKeyFromNotes() {
  var notes = [];
  for (var i = 0; i < arguments.length; ++i) notes[i] = arguments[i];
  // now notes is a plain array
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM