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));
asked Nov 17, 2015 at 6:37
Vijaykanth Dondapati
394 bronze badges
1 Answer 1
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
answered Nov 17, 2015 at 6:39
A.J. Uppal
19.3k7 gold badges48 silver badges82 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
indexOf, not the loop. Look up the documentation on it.