user584583
user584583

Reputation: 1280

adding item to array in jquery

I know this code is correct, I did not write it. I am trying to understand what the code is doing.

  1. create variable
  2. loop through unordered list's children
  3. set cssClass = class name
  4. if the cssClass is not in myarray, add it to myarray

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

Answers (4)

ipr101
ipr101

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

Bas Slagter
Bas Slagter

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

Dave Newton
Dave Newton

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

genesis
genesis

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

Related Questions