Looping through Photoshop layers in Javascript

送分小仙女□ 提交于 2020-01-04 02:03:42

问题


I'm trying to write a Photoshop script that will show all layers of a given name. I need to loop through all the possible nested layer sets and am using the following code:

function showBounds(layerNode)
{
    for(var layer in layerNode.artLayers)
    {
        if (layer.name == "@bounds")
        {
            layer.visible = 1;
        }
    }

    showBounds(layerNode.layerSets);
}

showBounds(app.activeDocument.doc.layerSets);

But when I run it, I get the following error:

Error 1302: No such element
Line: 5
->      for(var layer in layerNode.artLayers)

artLayers should be a property of LayerSets, so I'm confused.

This is also my first attempt at scripting PS (and using javascript), so there might be some fundamental concept I am not getting.


回答1:


I think you need something more like:

function showBounds(layerNode) {    
    for (var i=0; i<layerNode.length; i++) {

        showBounds(layerNode[i].layerSets);

        for(var layerIndex=0; layerIndex < layerNode[i].artLayers.length; layerIndex++) {
            var layer=layerNode[i].artLayers[layerIndex];
            if (layer.name == "@bounds") {
                layer.visible = 1;
            }
        }
    }
}

showBounds(app.activeDocument.layerSets);

Also, javascripts for...in syntax doesn't work the way you think it does. It's not like a foreach loop. It loops over the property names of an object.



来源:https://stackoverflow.com/questions/11333658/looping-through-photoshop-layers-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!