Created
July 1, 2011 08:59
-
-
Save cloud8421/1058128 to your computer and use it in GitHub Desktop.
Check for the presence of a value inside an array
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
# 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