Skip to content

Instantly share code, notes, and snippets.

@davidbarredo
Last active August 29, 2015 14:26
Show Gist options
  • Save davidbarredo/3b80a9350c5422457b2f to your computer and use it in GitHub Desktop.
Save davidbarredo/3b80a9350c5422457b2f to your computer and use it in GitHub Desktop.
Determine whether an array contains a value
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
@davidbarredo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment