Skip to main content
June 26, 2014
Question

Trying to understand Javascript collection numbers

  • June 26, 2014
  • 1 reply
  • 319 views

I found this bit in the Adobe introduction to scripting:

JS collection numbers are static; they don’t shift when you add a new object to the collection. Object

numbering in JS indicates the order in which the objects were added to the collection. Because the

first object you added was assigned the number 0, the next object you add to the collection is number

1; if you add a third object, it is number 2. For example, when you add a document, the document

automatically contains a layer. The layer’s index is [0]. If you add a layer, the new layer’s index is [1]; if

you add a second layer, its index is [2]. If you drag layer [2] to the bottom position in the Layers palette,

it still has index [2].

If I understand this correctly the original layer is always layer[0], however when I try this slightly modified script from later in the guide:

var myDoc = app.activeDocument

var myLayerCount = 4

for(var myCounter = 0; myCounter < myLayerCount; myCounter++)

{var myLayer = myDoc.layers[myCounter]

myLayer.visible = false}

the top 4 layers are set to invisible, while I was expecting it to be the bottom 4.

What am I missing?


This topic has been closed for replies.

1 reply

matias.kiviniemi
Legend
June 26, 2014

Two points:

  • doc.layers is a collection of all layers in document, regardless of the group it is in. This might not guarantee any order since they are "not in same list" (likely it's the order of layers-panel fully extracted). If you want to process layers in one group, you should use the .artLayers-collection
  • I think Photoshop processes layers from "top to bottom", i.e. both "from top of screen to bottom" in layers-panel and "from topmost to bottom" in z-order. If you want the other way, start from bottom.
June 27, 2014

layers or artLayers gives me the same results.

Would the processing order matter when it's looking for a specific layer index? If the layer index is static wouldn't this script start with layer 0 (the bottom one)?

matias.kiviniemi
Legend
June 27, 2014

If your document has no groups, then doc.layers and doc.artLayers will be the same. But if you groups then doc.layers will give all

  • art layers in the doc root
  • the groups you have an doc root
  • any art layers and sub groups in the root level groups.

I.e. doc.layers will return the full document hierarchy as a flat list, but the order that list is not guaranteed to be something (as far as I know). Most likely order is always the visual top to bottom. I.e. item 0 is always the visually topmost element.

Also note that if you use doc.layers, you need to check if the item is a layer or a group (=folder=layerset). That's why you also have the collections .artLayers and .layerSets that give just layers and groups respectfully.