Link to home
Start Free TrialLog in
Avatar of juan field
juan field

asked on

would you please explain me the conditional part ?

I had this question after viewing how can i count words?.
Avatar of hielo
hielo
Flag of Wallis and Futuna image

   ...
/* here str is split at the space, resulting in an array, which is assigned back to str variable.  So str ends up being converted onto an array or words. The for-construct iterates over this array. */
   str = str.split(" ");
   ...
     // key gets initialized to one of the words in the str array.
     key = str[i];

     // initially, result is initialized to an empty object => result={}.
     // In javascript, you can dereference an property using either of the following syntax:
     // result.ask
     // or
     // result['ask']
     // since I don't know the words ahead of time, I can't use the first form.  
     // So I used the second form, but used a variable instead of the literal word.
     // Initially, there is no such thing as result['ask'], so the else clause will execute
     // result['ask'] = 1; (but remember, the variable key contains 'ask' on the first iteration -- when i == 0)
     // The same logic applies for each word the first time they are encountered. 
     // Thus, when the second 'a' is encountered , result['a'] does exist -- it was initialized to 1 the first time around
     // So this time typeof(result['a']) is NOT "undefined" -- it was defined the first time it encountered 'a'.
     if( "undefined" != typeof(result[key]) )
        result[key]++;
     else
        result[key]=1;

Open in new window

Avatar of juan field
juan field

ASKER

@ hielo
thank you . i m still lost with the explanation . thanks anyways
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
much much better !!! i am reading and repeating the order . Thank you again.