JavaScript:如何循环遍历文件

4
我正在制作一个Illustrator CS6的Javascript,它可以执行以下操作:
  1. 打开一个Illustrator文件夹
  2. 打开文件夹中的每个文件(这些文件称为源文件)
  3. 选择源文件的所有内容
  4. 复制源文件的内容
  5. 创建一个新的目标文件,并将这些内容粘贴到目标文件中作为新图层
  6. 确保新图层与旧源文件同名
我的脚本可以工作,但是它不能正确地循环遍历源文件夹。相反,它只能在第一个源文件上正常运行。然后,它会无限地将第二个源文件粘贴到目标文档中(即它不会移动到任何其他源文件)。它只是无限地粘贴,所以我不得不强制退出!
如何使它正确地循环遍历文件夹并继续下一个文件。
以下是我的代码:
// JavaScript Document
//Set up vairaibles
var destDoc, sourceDoc, sourceFolder, newLayer;

// Select the source folder.
sourceFolder = Folder.selectDialog('Select the folder with Illustrator files that you want to mere into one', '~');
destDoc = app.documents.add();

// If a valid folder is selected
if (sourceFolder != null) {
    files = new Array();

    // Get all files matching the pattern
    files = sourceFolder.getFiles();

    if (files.length > 0) {
        // Get the destination to save the files
        for (i = 0; i < files.length; i++) {
            sourceDoc = app.open(files[i]); // returns the document object
            var myLayers = sourceDoc.layers; // Select All layers in Active Document
            //Go through all layers of source document and copy artwork
            for (i = 0; i < myLayers.length; i++) {
                myLayers[i].hasSelectedArtwork = true;
            };

            with(sourceDoc) {
                var count = pageItems.length;
                for (var i = 0; i < count; i++) {
                    pageItems[i].selected = true;
                }
                redraw();
                copy();
                for (var i = 0; i < count; i++) {
                    pageItems[i].selected = false;
                }


            }

            //Create a new title variable that has the title of the source document
            var title = sourceDoc.name;
            var title = title.substring(0, title.length - 4); //(remove extension from name)
            //Close the Source Document
            sourceDoc.close(SaveOptions.DONOTSAVECHANGES);

            //Open the Destination Document and create a new layer in it that is named after the title variation
            newLayer = destDoc.layers.add();
            newLayer.name = title;

            //Paste into this new layer
            newLayer = app.paste();

        }
    }
    else {
        alert('No matching files found');
    }
}

注:我不确定是否应该在Code ReviewGraphic Design上发布此内容,但我认为Stack Overflow是最好的地方,因为这是关于Javascript循环的一般问题,所以我希望这是正确的地方。

1个回答

5

看起来你在每个循环中都使用“i”作为变量,这会导致其他使用相同变量的循环中出现意外值的范围。我建议为每个循环使用单独的变量。例如:for j=0, for k=0, for l=0等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接