AS3: …(rest) parameter

This may look strange at the first sight. Actually this new keyword allows function to accept any number of arguments.


  1. function testing(...rest){
  2. trace(rest);
  3. }
  4. testing(1,2,'abc','def') // output: 1,2,abc,def

The arguments need to be separated by comma, and they will be stored into the array named "rest". It is not a must to name it "rest". You can use whatever names, just make sure you do not use other AS keywords.


  1. function testing2(...student){
  2. trace('There are ' + student.length + ' students'); //
  3. trace('The 1st student is '+ student[0]);
  4. trace('The 3rd student is '+ student[2]);
  5. }
  6. testing2('Peter','Mary','Albert','Joyce');
  7. /*
  8. output:
  9. There are 4 students
  10. The 1st student is Peter
  11. The 3rd student is Albert
  12. */

You can also use with other predefined parameters, and ...rest need to be the last parameter specified.


  1. function myFriends(myName, ...friends){
  2. trace('My name is ' + myName);
  3. trace('I have ' + friends.length + ' good friends. They are:');
  4. for(var i:int in friends){
  5. trace(friends[i]);
  6. }
  7. }
  8. myFriends('Peter','Mary','Joseph');
  9. /*
  10. output:
  11. My name is Peter
  12. I have 2 good friends. They are:
  13. Mary
  14. Joseph
  15. */

...rest is recommended instead of the arguments object. They are very similar, but the new ...rest do not have functionality like arguments.callee.

 

Back to the Tutorial index page