Vijaykanth Dondapati
Vijaykanth Dondapati

Reputation: 39

why we use -1 in javascript for loop?

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));

Upvotes: 0

Views: 47

Answers (1)

A.J. Uppal
A.J. Uppal

Reputation: 19264

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

Upvotes: 2

Related Questions