Copy link to clipboard
Copied
Hello Everyone,
I want to delete all the layers except one layer "art", I have written one script but it showing some error. Please help me to figure out.
I have attached the snippet and also the error code.
var document = app.activeDocument;
var lc = document.layers.length;
for (var i=1; i<=lc; i++) {
if (document.layers[i-1].name != "art")
{
document.layers[i].remove();
}
}
var document = app.activeDocument;
var lc = document.layers.length;
for (var i = lc - 1; i > -1; i--) {
if (document.layers[i].name != "art") {
document.layers[i].remove();
}
}
Another approach to avoid the issues very well explained by Mark could be to increment the counter only when the layer is not deleted. Try the following
var document = app.activeDocument;
for (var i = 0; i < document.layers.length;) {
if (document.layers[i].name != "art") {
document.layers[i].remove();
}
else
i++;
}
-Manan
Copy link to clipboard
Copied
var document = app.activeDocument;
var lc = document.layers.length;
for (var i = lc - 1; i > -1; i--) {
if (document.layers[i].name != "art") {
document.layers[i].remove();
}
}
Copy link to clipboard
Copied
@Surya24, just to explain what @femkeblanco's script is doing differently and why:
The for loop iterates over the document's layers *backwards* because of the way Extendscript references objects. It helps to think of the property "layers" of Document as being an array-like object that holds references to layers something like [layer 0 of document 0, layer 1 of document 0, layer 2 of document 0]
So the first iteration (i==0) removes the first layer of document 0, *which also is removed from the layers of document 0 object that you are iterating over*. Then the second iteration (i==1) is asking for index 1 of [layer 1 of document 0, layer 2 of document 0] but index 1 of this is *layer 2 of document 1*. This means it skipped a layer altogether!
Going backwards avoids this pitfall,
- Mark
Copy link to clipboard
Copied
Thank you so much for the explanation.
Copy link to clipboard
Copied
Thank you so much.
Copy link to clipboard
Copied
Thank you so much
Copy link to clipboard
Copied
Another approach to avoid the issues very well explained by Mark could be to increment the counter only when the layer is not deleted. Try the following
var document = app.activeDocument;
for (var i = 0; i < document.layers.length;) {
if (document.layers[i].name != "art") {
document.layers[i].remove();
}
else
i++;
}
-Manan
Copy link to clipboard
Copied
Thank you so much