javascript Javascript递归循环项到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19394051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript recursion loop items to array
提问by Jerry Walker
I am trying to make a small program that prompts a user to add items to a grocery list.
我正在尝试制作一个提示用户将项目添加到购物清单的小程序。
I read about using recursion to loop. I understand a while loop would probably be better suited for this task, but I ran into the same problems with the while loop and I wanted to try recursion. It just sounds like I know what I'm doing... "Yeh, I used recursion to enumerate the array while prompting validation from the user... hur hur hur"... but, I digress.
我阅读了关于使用递归循环的信息。我知道 while 循环可能更适合此任务,但我遇到了与 while 循环相同的问题,我想尝试递归。听起来我知道我在做什么……“是的,我使用递归来枚举数组,同时提示用户进行验证……呼呼呼呼”……但是,我离题了。
Here is the code:
这是代码:
function addToArray() {
var array = [];
array.push(prompt("Add items to array or 'q' to stop"));
if (array.pop() == 'q') {
document.write(array)
}
else {
addToArray();
}
}
addToArray();
If you'll notice, it loops like its supposed to but it is not adding items to an array. I have tried the array[i] = i
technique as well but to no avail, the array remains empty. Also, why is it that by using a function with no args am I not running into too much recursion? Is it because of the conditional statement?
如果您会注意到,它会像预期的那样循环,但不会向数组添加项目。我也尝试过该array[i] = i
技术,但无济于事,数组仍然为空。另外,为什么通过使用没有参数的函数我不会遇到太多递归?是不是因为条件语句?
If you know what I'm doing wrong, try and hint towards the right answer rather than just blurting it out. I'd like to have that 'Aha' moment. I think this all helps us learn a bit better.
如果你知道我做错了什么,试着暗示正确的答案,而不是脱口而出。我想要那个“啊哈”的时刻。我认为这一切都有助于我们更好地学习。
Thanks guys. (and gals)
多谢你们。(和女孩)
回答by user2736012
You're creating a new array instead of passing it to the recursive call.
您正在创建一个新数组,而不是将其传递给递归调用。
Do this instead.
改为这样做。
DEMO:http://jsfiddle.net/kDtZn/
演示:http ://jsfiddle.net/kDtZn/
function addToArray(array) {
array.push(prompt("Add items to array or 'q' to stop"));
if (array[array.length-1] == 'q') {
array.pop();
document.write(array)
}
else {
addToArray(array);
}
}
addToArray([]);
Now you start with an empty array, and for each recursive call, it passes the same array forward.
现在你从一个空数组开始,对于每个递归调用,它向前传递相同的数组。
Also, I changed it so that it doesn't use .pop()
in the if()
condition, otherwise you'll always end up with an empty array when it comes time to write it. (The .pop()
method actually removes the last item.)
另外,我改变了它,使它不使用.pop()
的if()
情况下,否则你将永远结束了一个空数组,当谈到时间来写它。(该.pop()
方法实际上删除了最后一项。)
Finally, make sure you're not using document.write
after the DOM is loaded. If so, you need to change it to use DOM manipulation methods instead.
最后,请确保在document.write
加载 DOM 后您没有使用。如果是这样,您需要将其更改为使用 DOM 操作方法。
You could take a different approach so that you don't need .pop()
at all.
你可以采取不同的方法,这样你就不需要.pop()
了。
DEMO:http://jsfiddle.net/kDtZn/1/
演示:http ://jsfiddle.net/kDtZn/1/
function addToArray(array) {
var item = prompt("Add items to array or 'q' to stop");
if (item == 'q') {
document.body.textContent = array;
} else {
array.push(item);
addToArray(array);
}
}
addToArray([]);
The reason your while
loop didn't work is very likely because of the original .pop()
issue.
您的while
循环不起作用的原因很可能是由于原始.pop()
问题。
回答by eugenekgn
Your function recreates var array = [] on every loop/recursion. I am not sure if recursion is the right tool for the job in your case - it does not seems like it - but if you're starting out with JavaScript/development and just trying it out then you're fine.
您的函数在每个循环/递归中重新创建 var array = []。我不确定递归是否是适合您的工作的正确工具 - 它似乎不是 - 但如果您开始使用 JavaScript/开发并尝试它,那么您很好。
回答by dogenpunk
While an 'infinite loop' is probably what you really want (as it would probably make the code simpler), you can do this with recursion by defaulting the array and passing it as an argument to the function. Like so...
虽然“无限循环”可能是您真正想要的(因为它可能会使代码更简单),但您可以通过默认数组并将其作为参数传递给函数来使用递归来实现。像这样...
function addToArray( array ) {
var array = array || [];
array.push(prompt( "Add items to array or 'q' to stop" ));
if ( array[array.length - 1] === 'q' ) {
document.write(array.slice( 0, -1 ))
} else {
addToArray( array );
}
}
addToArray();
There's two issues with the code as you presented. One, as pointed out earlier, you're redefining your array variable every time you call your function. Second, array.pop() alters your array, so when you get to the document.write call, you'd be printing an empty array anyways.
您提供的代码有两个问题。一,正如前面指出的,每次调用函数时都在重新定义数组变量。其次,array.pop() 改变了你的数组,所以当你调用 document.write 时,无论如何你都会打印一个空数组。