Javascript Array.include and Array.index

Just needed them and poor JS lacks these basic functions…

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;

3 thoughts on “Javascript Array.include and Array.index

  1. Comment went to the wrong post, wordpress bug?
    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.”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s