AS3: …(rest) parameter
This may look strange at the first sight. Actually this new keyword allows function to accept any number of arguments.
Actionscript:
-
function testing(...rest){
-
trace(rest);
-
}
-
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.
Actionscript:
-
function testing2(...student){
-
trace('There are ' + student.length + ' students'); //
-
trace('The 1st student is '+ student[0]);
-
trace('The 3rd student is '+ student[2]);
-
}
-
testing2('Peter','Mary','Albert','Joyce');
-
/*
-
output:
-
There are 4 students
-
The 1st student is Peter
-
The 3rd student is Albert
-
*/
You can also use with other predefined parameters, and ...rest need to be the last parameter specified.
Actionscript:
-
function myFriends(myName, ...friends){
-
trace('My name is ' + myName);
-
trace('I have ' + friends.length + ' good friends. They are:');
-
for(var i:int in friends){
-
trace(friends[i]);
-
}
-
}
-
myFriends('Peter','Mary','Joseph');
-
/*
-
output:
-
My name is Peter
-
I have 2 good friends. They are:
-
Mary
-
Joseph
-
*/
...rest is recommended instead of the arguments object. They are very similar, but the new ...rest do not have functionality like arguments.callee.
Thanks for the tutorial
Comment by John Giotta — July 27, 2006 @ 10:14 pm