Skip to content

Instantly share code, notes, and snippets.

@cloud8421
Created July 1, 2011 08:59
Show Gist options
  • Save cloud8421/1058128 to your computer and use it in GitHub Desktop.
Save cloud8421/1058128 to your computer and use it in GitHub Desktop.
Check for the presence of a value inside an array
# If you have an array and want to check the presence of a value inside it, there’s a very fast way:
arr = ['foo', 'bar', 'baz']
is_present = 'foo' in arr #returns true
isnt_present = 'hello' in arr #returns false
# Compiles down to:
`var arr, is_present, isnt_present;
var __indexOf = Array.prototype.indexOf || function(item) {
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] === item) return i;
}
return -1;
};
arr = ['foo', 'bar', 'baz'];
is_present = __indexOf.call(arr, 'foo') >= 0;
isnt_present = __indexOf.call(arr, 'hello') >= 0;`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment