[英]proper use of the array.push method
if I have a simple test function that adds even numbers to an array: 如果我有一个简单的测试函数,该函数将偶数加到数组中:
function isEven(n){
var enumbers = [];
if (n % 2 == 0){
enumbers.push (n);
}
}
how can I increment my parameter until I have a set number of members in my array? 在数组中有固定数量的成员之前,如何增加参数? for instance, I've tried this: 例如,我已经尝试过:
function isEven(n){
var enumbers = [];
while ( enumbers.length < 10){
if (n % 2 == 0){
enumbers.push (n);
}
console.log (enumbers);
n = n + 1;
isEven(n);
}
}
isEven(1);
but it seems to just create a new array for each number until it finally throws a range error (maximum call stack size exceeded). 但似乎只是为每个数字创建一个新数组,直到最终引发范围错误(超出最大调用堆栈大小)为止。
It's creating that array multiple times because you're constantly calling that function with: 它多次创建该数组,因为您经常使用以下命令调用该函数:
isEven(n);
You're also not comparing to the length of the array, just the array. 您还没有将数组的长度与数组的长度进行比较。 Add .length
to enumbers
. 将.length
添加到enumbers
。 Try changing to: 尝试更改为:
var enumbers = [];
while ( enumbers.length < 10){
if (n % 2 == 0){
enumbers.push (n);
}
console.log (enumbers);
}
The problem is that (enumber < 10) apparently always evaluates to true, causing an endless loop. 问题在于(enumber <10)显然总是评估为true,从而导致无限循环。 But it is this comparison that is wrong, since you're comparing an integer with an array I think you're trying to get the array length?: 但是这种比较是错误的,因为您正在将整数与数组进行比较,我想您正在尝试获取数组长度?:
while (enumbers.length < 10) {
Another thing. 另一件事。 enumbers is a local variable, so each call to isEven has it's own array. enumbers是一个局部变量,因此对isEven的每次调用都有其自己的数组。 Therefore, the functions is called recursively, over and over again. 因此,一次又一次地递归调用这些函数。
我建议您在is方法之外创建数组
I'm not sure if I understood your question. 我不确定是否理解您的问题。 But you shouldn't use global variables, and it is unnecessary to call your function recursively inside a while loop. 但是,您不应该使用全局变量,并且没有必要在while循环内递归调用函数。
The error maximum call stack size exceeded
is your browser trying to break a infinity loop. 错误maximum call stack size exceeded
是您的浏览器试图打破无限循环。
This is what you need. 这就是你所需要的。
Examples here jsFiddle1 and jsFiddle2 此处的示例jsFiddle1和jsFiddle2
function isEven(n) {
var enumbers = [];
while (enumbers.length < 10) {
if (n % 2 == 0) {
enumbers.push(n);
}
n++;
}
return enumbers;
}
Setup a test 设置测试
var n = 1;
var evenArray = isEven(n); //call isEven function and it returns an array
document.body.innerHTML = evenArray; //2,4,6,8,10,12,14,16,18,20
I would have written something like: 我会写一些像:
function isEven(n,enumbers){
while(enumbers < 10){
if (n % 2 == 0){
enumbers.push (n);
}
console.log (enumbers);
n = n + 1;
isEven(n, enumbers);
}
}
var enumbers = [];
isEven(1,enumbers);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.