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

asked Nov 17, 2015 at 6:37
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

answered Nov 17, 2015 at 6:39
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.