Just needed them and poor JS lacks these basic functions…
Warning:
if(![‘hello’].index(‘hello’))alert(‘watch out because 0 is false‘);
Array.prototype.index = function(val) { for(var i = 0, l = this.length; i < l; i++) { if(this[i] == val) return i; } return null; } Array.prototype.include = function(val) { return this.index(val) !== null; }
Comment went to the wrong post, wordpress bug?
jafferhaider.wordpress.com:
Wouldn’t it be better if you returned -1 instead of null in the index function?
Its build to be ruby-like:
Array.index: “Returns the index of the first object in self such that is == to obj. Returns nil if no match is found.”
*double checks the title of the post* 😉
Ah ok, makes sense.
Simple and efficient!