简体   繁体   中英

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.

/// 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 . 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 . So the loop never finishes, because the index x never reaches the ever increasing 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 . 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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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