1 Reply Latest reply on Nov 27, 2013 6:38 AM by Jump_Over

    [JS][CC] checking an Array using IndexOf

    Roy Marshall Level 1

      Hi.

       

      I have no idea if this will help others, or if I have over complicated the issue, but wanted to share a recent issue I had.

       

      I was writing a script and wanted to check the contents of an array, and add the value if it was not already in the Array using IndexOf as below:

      (I was buidling up an array of used paragraph styles, as it happens)

       

      function pushUnique(arrayName,valueToCheck){

                var myIndex = arrayName.indexOf(valueToCheck);

                if(myIndex==-1){

                          arrayName.push(valueToCheck);

                          }

                }

       

       

      However, I was unable to use IndexOf on the array.

       

      Adding the following code at the top of my Library file, added the IndexOf prototype to the Array object, and made it work fine!

       

       

       

      Array.prototype.indexOf = function ( item ) {

                var index = 0, length = this.length;

                for ( ; index < length; index++ ) {

                          if ( this[index] === item )

                                    return index;

                }

                return -1;

                };

       

       

      Any thoughts on this would be good, is this good/bad practice to be messing with the Objects prototypes?

       

      This tip is from a Javascript Developer who is very knowledgeable on Javascript, but never used the InDesign DOM. (my Son)

        • 1. Re: [JS][CC] checking an Array using IndexOf
          Jump_Over Level 5

          Hi,

           

          I suggest to combine 2 in 1:

          I.e.:

          Array.prototype.pushUnique = function (item) {
               var push = true;
               for (var k = 0; k < this.length; k++)
                    if (this[k] == item) {push = false; break }
               if (push) this.push(item);
               }
          
          myArray.pushUnique(value);
          

           

          ... or the same with a 'function' way. As far as I know the difference is prototype RAM consuming (if many objects present) but that's only what I read about somewhere..., can't prove it

           

          Jarek