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 idiom 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; 

Need Your Help

jQuery UI Draggable: Stack on Click

javascript jquery jquery-ui

Is there any way to kick off a draggable's stack procedure when it is clicked, not just dragged?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.