I'm trying to write a script that toggles the specific layers that I enter into a prompt window, but I keep getting "namesArray.indexOf is not a function". Here is the code-
// Prompt the user for comma-separated layer names
var layerNames = prompt("Enter layer names separated by commas:");
// Convert the input string into an array of names
var namesArray = layerNames.split(",");
// Loop through all layers in the document
for (var i = 0; i < app.activeDocument.layers.length; i++) {
var layer = app.activeDocument.layers[i];
// Toggle visibility for layers with matching names
if (namesArray.indexOf(layer.name) >= 0) {
layer.visible = !layer.visible;
}
}
How do I go about fixing this error?
It seems that Photoshop's version of indexOf only works on strings - it doesn't work on your array. I get the same error. I can only think that the version of ECMA script that Photoshop uses is so antique that the above is true. See here for more details.
A quick workaround is to add a function that does the same trick:
// Prompt the user for comma-separated layer names
var layerNames = prompt("Enter layer names separated by commas:");
// Convert the input string into an array of names
var namesArray = layerNames.split(",");
// Loop through all layers in the document
for (var i = 0; i < app.activeDocument.layers.length; i++)
{
var layer = app.activeDocument.layers[i];
var idx = get_index(namesArray, layer.name);
// Toggle visibility for layers with matching names
// if (namesArray.indexOf(layer.name) >= 0)
if (idx >= 0)
{
layer.visible = !layer.visible;
}
}
function get_index(arr, str)
{
for (var i = 0; i < arr.length; i++)
{
if (arr[i] == str) return i;
}
}