1 Reply Latest reply on Feb 17, 2011 12:56 PM by flavioflavio

    how to add results (numbers) from a search? [newbie]

    flavioflavio

      Hi there,

       

      I know this will probably sound very basic but I'm stuck with a simple issue:

       

      Let's say I have a simple text:

       

      1, 2, 3

       

      I then do a search for the digits and convert them into numbers:

       

      var myDocument = app.activeDocument;
      var myStory = myDocument.stories.item(0);
      
      app.findTextPreferences = app.changeTextPreferences = app.findGrepPreferences = app.changeGrepPreferences = null;
      
      app.findGrepPreferences.findWhat = "\\d";
      var myFoundGrep = myStory.findGrep();
      
      for (i=0;i<myFoundGrep.length;i++){
           //var myNumbers = myFoundGrep[i].contents;
           var myNumbers = parseInt(myFoundGrep[i].contents);
              }          
      

       

      I can see using "constructor.name" that the results of my search (1 2 3) are now numbers and are stored in myNumbers - even though they cannot be accessed using myNumbers[0] or myNumbers[1], for example.

       

      The question is: how do I add them (1 + 2 + 3 = 6)?

       

      I tried doing (inside the loop):

       

      var myTest = 0;
      myTest += myNumbers;
      

       

      But it will always give me the last number (3) as a result and not the sum of them all (6)...

       

      This is probably very basic, but I've spent the whole afternoon looking for a way of doing this and am now pretty lost... Any suggestions?

       

      thanks,

      flavio

        • 1. Re: how to add results (numbers) from a search? [newbie]
          flavioflavio Level 1

          I knew this was probably something very basic. I had to declare the variable outside the loop. The code goes below:

           

          var myDocument = app.activeDocument;
          var myStory = myDocument.stories.item(0);
          
          app.findTextPreferences = app.changeTextPreferences = app.findGrepPreferences = app.changeGrepPreferences = null;
          app.findGrepPreferences.findWhat = "\\d";
          var myFoundGrep = myStory.findGrep();
          var myAddingNumbers = 0;
          
          for (i=0;i<myFoundGrep.length;i++){
               myAddingNumbers += parseInt(myFoundGrep[i].contents);     
               }
          alert (''+myAddingNumbers+'');
          

           

          I'll mark it as answered. Cheers.