Last active
August 29, 2015 14:26
-
-
Save davidbarredo/3b80a9350c5422457b2f to your computer and use it in GitHub Desktop.
Determine whether an array contains a value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var indexOf = function(needle) { | |
if(typeof Array.prototype.indexOf === 'function') { | |
indexOf = Array.prototype.indexOf; | |
} else { | |
indexOf = function(needle) { | |
var i = -1, index = -1; | |
for(i = 0; i < this.length; i++) { | |
if(this[i] === needle) { | |
index = i; | |
break; | |
} | |
} | |
return index; | |
}; | |
} | |
return indexOf.call(this, needle); | |
}; | |
// You can use it like this: | |
var myArray = [0,1,2], | |
var needle = 1, | |
var index = indexOf.call(myArray, needle); // 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From: http://stackoverflow.com/a/1181586