3

Photoshop CC 2017. Using this loop to delete paths one by one results in some paths (out of 8) being deleted only:

 for(i = 0; i < app.activeDocument.pathItems.length; i++) {
             alert(i)
             app.activeDocument.pathItems[i].remove();
        }   

The length gets reported as being 8. However alert(i) only shows 4 times. All the paths get removed only if running the loop multiple times. I'm deleting them one by one because I want to keep a path with a certain name. Any ideas?

CristianC
  • 303
  • 3
  • 11
  • 2
    Possible duplicate of [Looping through array and removing items, without breaking for loop](https://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop) – Ivar Oct 04 '17 at 07:17
  • 1
    Basically, you are removing an item, which decrements the `.length`. You also increment the `i`, so by the time your `i` = 4, you only have 4 items left in your array, so it is finished. – Ivar Oct 04 '17 at 07:21
  • Thank you Ivar, that's the solution! – CristianC Oct 04 '17 at 07:21

2 Answers2

1

You are changing pathItems as you loop through it. When you delete item i there will be a new item at position i that you skip. If you do the loop backwards it won't cause any problems

 for(i = app.activeDocument.pathItems.length -1; i >= 0; i--) {
    alert(i)
    app.activeDocument.pathItems[i].remove();
 } 
tallberg
  • 429
  • 3
  • 12
  • Yes this also works. I also discovered using Ivar's comment I can loop through the array backwards. I believe using the while loop to delete the [0] element will cause problems if I want to keep a certain element(with a certain name). – CristianC Oct 04 '17 at 07:25
1

You can use pathItems.removeAll() in this case.

Tim Harding
  • 299
  • 1
  • 12