0

why we use -1 in javascript for loop

the example code here

var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];

function squash(arr){
    var tmp = [];
    for(var i = 0; i < arr.length; i++){
        if(tmp.indexOf(arr[i]) == -1){
        tmp.push(arr[i]);
        }
    }
    return tmp;
}

console.log(squash(arr));

1
  • 2
    You use it for indexOf, not the loop. Look up the documentation on it. Commented Nov 17, 2015 at 6:38

1 Answer 1

2

The indexOf function returns -1 if the item is not found in the desired array.

document.write([1, 2, 3].indexOf(1)+" "); //Exists
document.write([1, 2, 3].indexOf(0)); //Does not exist

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.