CeeJay
CeeJay

Reputation: 599

Why the loop stops right in the middle?

I am trying to solve Lucky Sevens problem where you need to return true if any 3 consecutive numbers in an array sum to 7. I know there is a better way to do it, but I want to use .splice here. For some reason the loop stops in the middle and don’t check the last six digits.

function seven(arr) {
    for(var i=0; i<arr.length; i++) {
        if((arr[0] + arr[1] + arr[2]) == 7) {
            document.body.innerHTML = “true”;
        }
        arr.splice(0,1);
        document.body.innerHTML = “false”;
}}
seven([1,5,7,1,5,2,1,5,3,1,5,1]);

Upvotes: 0

Views: 80

Answers (3)

Saqib A. Azhar
Saqib A. Azhar

Reputation: 1074

Its because value of "i" becomes equal to length of "arr" array after 5th iteration, condition

i < arr.length 

in your loop stops the execution of for loop.

Upvotes: 0

Eftakhar
Eftakhar

Reputation: 455

You are deleting the arr element in the loop at arr.splice(0,1); and in the loop break condition i<arr.length; the length gets calculated at every iteration. So when you use splice the array changes and in arr.length will give you new length of array.

The solution with splice

function seven(arr) {
var len = arr.length
    for(var i=0; i<len; i++) {
        if((arr[0] + arr[1] + arr[2]) == 7) {
            document.body.innerHTML = “true”;
        }
        arr.splice(0,1);
        document.body.innerHTML = “false”;
}}
seven([1,5,7,1,5,2,1,5,3,1,5,1]);

without splice

function seven(arr) {
    var len = arr.length -2
        for(var i=0; i<len; i++) {
            if((arr[i] + arr[i+1] + arr[i+2]) == 7) {
                document.body.innerHTML = “true”;
            }
            document.body.innerHTML = “false”;
    }}
    seven([1,5,7,1,5,2,1,5,3,1,5,1]);

Upvotes: 0

Adrian
Adrian

Reputation: 8597

Use a while loop.

function seven(arr) {
    while(arr.length > 2) {
        if((arr[0] + arr[1] + arr[2]) == 7) {
            document.body.innerHTML = "true";
        }
        arr.splice(0,1);
        document.body.innerHTML = "false";
    }
}
seven([1,5,7,1,5,2,1,5,3,1,5,1]);

The loop will break if there are 2 elements but will run for the duration of existence of more than 2 elements in the array.

Upvotes: 1

Related Questions