Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created July 12, 2011 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/1077593 to your computer and use it in GitHub Desktop.
Save Integralist/1077593 to your computer and use it in GitHub Desktop.
Cheap 'inArray' trick by @ded
/*
* jsFiddle: http://jsfiddle.net/integralist/fL2Xv/
* Original: http://twitter.com/#!/ded/status/90531502097575936
*/
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(item) {
return ( Math.abs( ~this.indexOf(item) ) )-1;
}
}
@mathiasbynens
Copy link

if (!Array.prototype.indexOf) {} could be shortened to if (![].indexOf) {}.

@Integralist
Copy link
Author

Yep, I probably would do that in a production script, but for the purpose of example it just makes it clearer (in my opinion).

Not that [].indexOf is more complicated or confusing in any way I just find the long winded route more appropriate for examples like this :-)

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