Reputation: 1280
I know this code is correct, I did not write it. I am trying to understand what the code is doing.
I am familiar with other ways to check to see if an item is in an array, and familiar with other ways to add an item to an array, but this method confuses me. Do other languages support this type of syntax?
var myarray = [];
$(".somelist > li").each(function() {
var cssClass = $(this).attr("class");
//This part below is CONFUSING
if(!myarray[cssClass]) {
myarray[cssClass] = true;
}
});
Upvotes: 0
Views: 126
Reputation: 24236
1 if(!myarray[cssClass]) {
2 myarray[cssClass] = true;
}
Here's a brief outline of what's happening, the myarray
variable is used as a hash -
1 - Checks to see if the current class name is in the array. myarray[cssClass]
will return a 'falsy' value if the class name is not conatined in the array.
2 - If the class is not in the array, add it to the array and set it's value to true
Upvotes: 1
Reputation: 9929
If the array does not contain an entry with the key represented by the cssClass variable it will add it and set the value of that key to true. If it already exists, it stays true...so
if(!myarray[cssClass]))
returns false if there is no key with the value that is set to the cssClass variable. I don't know the context of this code but from this point it seems a bit useless.
Upvotes: 1
Reputation: 160191
If the hash/map doesn't contain an entry for the given class, add it.
It's creating a collection of all the classes used by list items in the somelist class.
Upvotes: 2
Reputation: 50976
In this case, it will be false only if it's first occurence of that array. When it's second loop and class is the same, it won't change it to true
again. It makes no sense though. This code is synonym of
var myarray = [];
$(".somelist > li").each(function() {
var cssClass = $(this).attr("class");
myarray[cssClass] = true;
});
Upvotes: 1