function showMyLayers() {
var Mylayers = [
["ISO"],
["ODO"],
["Black Round Mask"],
["red glow on gauges"],
["Compass"],
["4 Gauges"],
["Upper Stainless Steel"],
["Background"]
];
for (x in Mylayers) {
var activelayer = app.activeDocument.layers[x];
activelayer.visible = true;
activelayer = null;
}
} showMyLayers();
it e开发者_JAVA技巧rrors out on: ["4 Gauges"],
assuming the number is messing with the array. any ideas why? this is extendscript which is javascript but for photoshop in case you're wondering. but its based on JS for most part so it should behave like it.
The for..in
loop is to iterate over objects. To iterate over arrays, use a classic for
loop. Further more, what you have there is an array of array, which is probably not what you want.
var Mylayers = [
"ISO",
"ODO",
"Black Round Mask",
"red glow on gauges",
"Compass",
"4 Gauges",
"Upper Stainless Steel",
"Background"
];
for (var i = 0; i < Mylayers.length; i++) {
var x = Mylayers[i];
var activelayer = app.activeDocument.layers[x];
activelayer.visible = true;
activelayer = null;
}
Ah... Adobe JavaScript...
Your issue is that you're actually looping through the indexes of the array, and not the values. So, you probably have a layer 0...4, but layer 5 is probably a folder.
Recommendations:
- You're using nested arrays instead of strings. I would get rid of the
[]
around the items in the array. - Instead of
for( x in Mylayers )
and then using x, usefor(x in Mylayers){ var tmp = Mylayers[x]
- I am not certain about ExtendScript, but in JSFL (the equivalent for Flash) the way to get access to a layer object was layers[timeline.getLayerIndex(layerName)]
I don't think you're doing what you think you're doing. The for..in loop in Javascript isn't a foreach loop that you might be used to, and in most cases is a poor choice for looping over arrays. Instead of setting x
to an instance element in the array, it sets x
to the next key in the object. In this case, a numeric value (0, 1, 2...). Unfortunately, it will also loop over object properties on your Array instance (length, forEach, etc).
You really should be using a regular for loop:
var MyLayers = [ 'foo', 'bar', 'baz' ];
for(var i = 0; i < MyLayers.length; i += 1) {
app.activeDocument.layers[MyLayers[i]].visible = true;
}
You also don't need to explicitly set things to null. Javascript is memory managed.
精彩评论