简体   繁体   English

递归函数还是在javascript中循环?

[英]Recursive function or loop in javascript?

I am trying to write a recursive function, but I am completely lost as to how to implement it. 我试图编写一个递归函数,但是我完全不知道如何实现它。 I currently have the following: 我目前有以下内容:

function change(p){
    // code for function
}

var c1 = change(start);
var c2 = change(c1);
var c3 = change(c2);
// etc. etc.

Is there any way to do this with a while loop? 有什么办法可以使用while循环吗? For example: 例如:

while(currentResultofFunction != goal)
    nestedly loop through as before until reaches true
function change(p) {
    if (p != 1) { // your condition
        change(p);
    } else return p;
}

What about: 关于什么:

var val = start;
while(val) //or while val != goal
  val = change(val);

What you are doing, is not recursive. 您正在执行的操作不是递归的。 You maybe mean iterative . 您可能会说迭代

You can loop through the variables in this way: 您可以通过以下方式遍历变量:

var n = 2;
for (var i = 1; i <= n; i++) {
  if (i == 1) window['c1'] = change(start);
  else window['c' + i] = change(window['c' + (i - 1)]);
}

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

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