简体   繁体   中英

Incremental while loop becomes infinite

I'm trying to create a new folder with an ascending number on the end if a folder already exists, but I end up in an infinite loop

var i=1;
while (myFolder.exists == true) {
var myFolder = new Folder(wf+"/"+curFile+"_folder"+i)
i++;
};

Any help would be appreciated.

It looks like myFolder.exists is a method, not a property, so you have to call it:

while (myFolder.exists()) {
    var myFolder = new Folder(wf + "/" + curFile + "_folder" + i);
    i++;
};

Otherwise, you would be evaluating the method itself, which is indeed always true in a boolean context.

Note in passing that redefining myFolder inside the loop is probably not the problem here. Loops in Javascript share the same scope as the enclosing code, and the variable will be hoisted to the start of that scope. As jdwire says, it can be undefined initially, but then you would receive an error instead of triggering an infinite loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM