[英]Why this for loop is infinite loop despite a condition?
This function below is to create array slice and push is giving infinite loop. 下面的此函数用于创建数组切片,而推推则给出无限循环。 Can anybody try to justify that.
任何人都可以尝试证明这一点。
function MyFunction(arr, size) {
var newArr = [];
for(var i=0; i<arr.length; i+size)
{
newArr.push(arr.slice(i,i+size));
}
return newArr;
}
I am able to achieve my requirement with below while loop, although it seems almost similar. 尽管看起来几乎相似,但我可以通过下面的while循环达到我的要求。
function MyFunction(arr, size) {
var newArr = [];
var i = 0;
while(i < arr.length)
{
newArr.push(arr.slice(i,i+size));
i = i + size;
}
return newArr;
}
Sample Input :- myFunction(["a", "b", "c", "d"], 2);
样本输入 :-myFunction([“ a”,“ b”,“ c”,“ d”],2);
Sample Output :- [["a", "b"], ["c", "d"]]
样本输出 :-[[“ a”,“ b”],[“ c”,“ d”]]
I think i+size
should be i += size
or i = i + size
. 我认为
i+size
应该是i += size
或i = i + size
。
In the first loop, you're never incrementing i
. 在第一个循环中,您永远不会递增
i
。
EDIT 编辑
You may also want to change the body of the loop to match the while
loop too. 您可能还想更改循环的主体以匹配
while
循环。
Eg, putting it all together, this for
loop should be the equivalent of your while
loop: 例如,将它们放在一起,此
for
循环应与while
循环等效:
for (var i = 0; i < arr.length; i += size) {
newArr.push(arr.slice(i, i + size));
}
In your for loop you are never incrementing your variable i
. 在for循环中,您永远不会增加变量
i
。 That is it. 这就对了。
i++
auto increments i
but i+size
doesn't. i++
自动递增i
但i+size
不递增。
it should be i=i+size
or i+=size
; 它应该是
i=i+size
或i+=size
;
Hope this helps. 希望这可以帮助。
Edit 编辑
Your for loop should be:- 您的for循环应为:-
function MyFunction(arr, size) {
var newArr = [];
for(var i=0; i<arr.length; i = i+size)
{
newArr.push(arr.slice(0,size));
}
return newArr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.