数组在循环遍历时表现得很奇怪
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();
它出错了: [“4 Gauges”],
假设数字扰乱了数组。有什么想法为什么吗?这是extendscript,它是javascript,但适用于photoshop,以防您想知道。但它大部分基于 JS,所以它的行为应该像它一样。
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 errors 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
for..in
循环用于迭代对象。要迭代数组,请使用经典的for
循环。此外,你拥有的是一个数组的数组,这可能不是你想要的。The
for..in
loop is to iterate over objects. To iterate over arrays, use a classicfor
loop. Further more, what you have there is an array of array, which is probably not what you want.啊... Adobe JavaScript...
您的问题是您实际上是在循环数组的索引,而不是值。因此,您可能有一个层 0...4,但层 5 可能是一个文件夹。
建议:
[]
。for( x in Mylayers )
然后使用 x,而是使用for(x in Mylayers){ var tmp = Mylayers[x]
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:
[]
around the items in the array.for( x in Mylayers )
and then using x, usefor(x in Mylayers){ var tmp = Mylayers[x]
我不认为你在做你认为你在做的事情。 Javascript 中的 for..in 循环不是您可能习惯的 foreach 循环,并且在大多数情况下对于循环数组来说是一个糟糕的选择。它将
x
设置为对象中的下一个键,而不是将x
设置为数组中的实例元素。在本例中,为数值 (0, 1, 2...)。不幸的是,它还会循环遍历 Array 实例上的对象属性(length、forEach 等)。您确实应该使用常规的 for 循环:
您也不需要显式地将内容设置为 null。 JavaScript 是内存管理的。
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 setsx
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:
You also don't need to explicitly set things to null. Javascript is memory managed.