ActionScript 3 - Using Associative Array to count occurrences
Hey everyone, in many programming languages there is this great idiom that lets you use a hash to count occurrences of items. Eg in Perl, suppose you have a list of students and you want to see how many of each name you have (2 Bobs, 1 Jeremy, 22 Aidans etc):
my %uniqueNames;
for (@studentNames){ $uniqueNames{$_}++; }
# print it out
for (keys %uniqueNames){ print "$_ : $uniqueNames{$_}\n"; }
So you can do this in ActionScript 3 of course, using the Object.
The problem is NaN. If you try to autocreate and autoincrement a key at the same time, you get NaN, and the whole thing breaks down.
Sure, you can use a conditional to test whether the key exists, and then autoincrement it, or set it to one if not, but that's ugly.
studentNames[name] = studentNames[name] ? studentNames[name] + 1 : 1; // shudder
What's the correct idio开发者_JS百科m for AS3? Is there an idiom? YOU'RE an idiom. -- T
Your answer is correct but you can do the same in a shorter way :
studentNames[name] = (studentNames[name] || 0) + 1;
Ain't nothing wrong here... move along, idiom. Seriously, what you've done is fine.
精彩评论