简体   繁体   English

递增的while循环变为无限

[英]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: 看起来 myFolder.exists是一个方法,而不是属性,因此您必须调用它:

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. 否则,您将对方法本身进行评估,在布尔上下文中确实总是true

Note in passing that redefining myFolder inside the loop is probably not the problem here. 请注意,在循环中重新定义myFolder可能不是这里的问题。 Loops in Javascript share the same scope as the enclosing code, and the variable will be hoisted to the start of that scope. Javascript中的循环与封闭代码共享相同的作用域,并且变量将被提升到该作用域的开始。 As jdwire says, it can be undefined initially, but then you would receive an error instead of triggering an infinite loop. 正如jdwire所说,它最初可能是undefined ,但是随后您将收到错误,而不是触发无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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