Reputation: 252
I'm not very advanced in coding, but I want to do something like this:
function something(id){
somethingElse(id);
anotherThing(id);
}
var sampleArray:Array = [1,2,3];
something(1);
something(2);
something(3);
BUT, I want it to keep function with the argument of each item in the array one time no matter how long the array is.
Any help?
Upvotes: 0
Views: 56
Reputation: 408
Here's how you can apply function something(array_element)
to an arbitrary length array:
sampleArray.forEach(something);
It will not allow you to mutate the elements within the Array, however (unless they themselves contain references to other items and you're changing that).
REF: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html
Examples:
It's been a while since I messed with doing AS3.
The following is expected to be inside an AS3 class definition and provides a public function that takes a Vector of uints and accumulates the greater than two uints:
private var _greater_than_two:Vector<uint>;
private function _append_greater_than_two(item:uint):void {
if (item > 2) {
_greater_than_two.push(item);
}
}
// Ok, We're assuming that the array is strictly typed and full of uints.
public function collect_greater_than_twos(items:Vector<uint>) {
// Append to the class instance _greater_than_two Vector any uint that is greater than two:
items.forEach(_append_greater_than_two);
// Tell us what is inside _greater_than_two now:
trace("The _greater_than_two Vector has " + contents.join(', '));
}
Another use case may be to conditionally add to a Database. Let's assume we're building a MMORPG and you want to track how many times a player says "Hodor".
The below is, again, assuming this is inside a class (Let's call it Player):
private _redis:Redis; //assuming you filled this value in the constructor
private _playerName:String;
private function _detect_hodors(action:String):void {
if (action.indexOf('Hodor') > -1) {
_redis.incr(_playerName + 'actions', 1);
}
}
public function process_user_actions(actions:Vector<String>):void {
actions.forEach(_detect_hodors);
// Do other things here...
}
A lot of companies will prefer you express the above in a simple for loop (assuming we're using the _append_greater_than_twos function from above):
function collect_greater_than_twos(items:Array):void {
var index:uint;
var item:uint;
var end:uint = items.length;
for (index=0; index < end; index++) {
item = items[index] as uint;
_append_greater_than_twos(item);
}
}
When I was doing AS3, we avoided foreach constructs because they were much slower than using bare for loops and index accesses. Things could've changed since then though.
Upvotes: 2
Reputation: 215
Try something like:
function something(id):void{
somethingElse(id);
anotherThing(id);
}
var sampleArray:Array = [1,2,3];
something(sampleArray[0]);
something(sampleArray[1]);
something(sampleArray[2]);
Upvotes: 0