#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    3
    Rep Power
    0

    Question about this peice of JS code


    Code:
    function LongestWord(sen) { 
    
      
      var v = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
          lng = '',
          lngn = 0,
          ss = sen.split(' ');
      
      for (var i = 0; i < ss.length; i++) {
        var c = 0, s = '';
        for (var j = 0; j < ss[i].length; j++) {
          if (v.indexOf(ss[i][j]) >= 0) {
            c++;
            s += ss[i][j];
          }
        }
        
        if (c > lngn) {
          lngn = c;
          lng = s;
        }
      }
      
      // code goes here
      return lng; 
                
    }
    This is larger piece of code. The point here is to find the largest word in a string. The part that I'm having trouble understand is:

    Code:
    for (var i = 0; i < ss.length; i++) {
        var c = 0, s = '';
        for (var j = 0; j < ss[i].length; j++) {
          if (v.indexOf(ss[i][j]) >= 0) {
            c++;
            s += ss[i][j];
          }
        }
    Mainly because of the nested for statements. I understand that we're essentially iterating through the sentence and the alphabet presented. But I'm a little confused once we hit the indexOf segment. How does marking ss[i][j] work? Does this mean that ss is iterating through both at the same time?

    If someone could help explain this in laymen's terms it would be greatly appreciated.
  2. #2
  3. Lord of the Dance
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2003
    Posts
    3,534
    Rep Power
    1906
    the parameter sen can be a list of word separated by spaces.
    ss[i] is used to iterate through each word.
    ss[i][j] is used to iterate through each character for the word at index i.

    Comments on this post

    • xelad1 agrees : Thanks for the help!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    3
    Rep Power
    0
    Originally Posted by MrFujin
    the parameter sen can be a list of word separated by spaces.
    ss[i] is used to iterate through each word.
    ss[i][j] is used to iterate through each character for the word at index i.
    Oh ok. That makes sense, thank you!

IMN logo majestic logo threadwatch logo seochat tools logo