简体   繁体   English

Javascript:Unshift()导致无限循环,但看不到原因

[英]Javascript: Unshift() is causing an infinite loop but can't see why

I am trying to make a function that takes an array and returns the array with the even numbers before the odd numbers. 我正在尝试制作一个函数,该函数需要一个数组,并在奇数之前返回带有偶数的数组。 I figured I'd iterate through the array and check the divisibility of each number with modulo. 我以为我要遍历数组,并用模来检查每个数字的可除性。 If it's an even number, I unshift that number to the front of the array and keep going. 如果是偶数,则将该数字移到数组的开头并继续操作。

I've removed unshift to log that it iterates through so I know the issue isn't with my loop. 我删除了unshift来记录迭代过程,因此我知道问题不在我的循环中。

/// A = [3,5,6,3,4,2,1]

var sortArrayByParity = function(A) {
    for (var x =0; x< A.length;x++) {
        if (A[x] % 2 == 0) {
           A.unshift(A[x])
        } 
    }
    return A;
};

Maximum stack error is occuring. 发生最大堆栈错误。

Because unshift adds an element to the array, thereby increasing its length . 因为unshift将元素添加到数组,从而增加了它的length Furthermore, once the unshift adds an element to the beginning of the array, the next A[x] is the same as the previous one, as all elements get moved to the right, including x . 此外,一旦unshift将元素添加到数组的开头,下一个A[x]与上一个相同,因为所有元素(包括x向右移动。 So the loop never finishes, because the index x never reaches the ever increasing length . 因此循环永远不会结束,因为索引x永远不会达到不断增加的length

If you need to add elements to an array through which you are iterating with a loop, it's better to do it with push in a loop that counts downwards from length to 0 . 如果您需要向循环中迭代的数组中添加元素,则最好通过push入一个从length0递减的循环来实现。 That way, the loop will never iterate through added elements, and the elements that it will iterate through will not move. 这样,循环将永远不会遍历添加的元素,并且它将遍历的元素不会移动。

When you unshift an array an element is added to the start of that array and increase the length. 取消移动数组时,会将元素添加到该数组的开头并增加长度。

Lets try 我们试试吧

 let arr = [1]; console.log('arr = ',arr, 'length =', arr.length); arr.unshift(0); console.log('arr = ',arr, 'length =', arr.length); 

As a result when you find a even number you unshift it to the front but it will also be available in x + 1 position. 结果,当您找到一个偶数时,可以将其移到最前面,但是在x +1位置也可以使用。 and as you iterate you will find the same even number in next iteration. 当您进行迭代时,您将在下一次迭代中找到相同的偶数。

correct implementation would be. 正确的实施是。

 /// A = [3,5,6,3,4,2,1] var sortArrayByParity = function(A) { for (var x =0; x< A.length;x++) { if (A[x] % 2 == 0) { A.unshift(A[x]); A.splice(x+1, 1); } } return A; }; console.log(sortArrayByParity([3,5,6,3,4,2,1])); 

You should use both unshift and splice . 您应该同时使用unshiftsplice

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

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