To determine whether an array contains an element of a JS function implementation method _javascript tips

Source: Internet
Author: User

A method of realizing the JS function of whether an array contains an element

Array.prototype.contains = function (obj) {
  var i = this.length;
  while (i--) {
    if (this[i] = = obj) {return
      true;
    }
  }
  return false;
}

Or

Array.prototype.contains = function (Element) {for
  (var i = 0; i < this.length; i++) {
    if (this[i] = = Element ) {return
      true;
    }
  }
  return false;
}

Or

Array.prototype.in_array = function (e) {for
  (i=0; i<this.length && this[i]!=e; i++);
  Return! (i==this.length);
}

There's another Daniel who wrote this:

ARRAY.PROTOTYPE.S = String.fromCharCode (2);
Array.prototype.in_array = function (e) {
  var r = new RegExp (this. S+e+this. S);
  Return (R.test) (this. S+this.join (this. S) +this. S));
}

The use method is:

var arr=["A", "B"];

Alert (Arr.in_array ("a"))

While minus iteration is said to be the fastest way in JS, do not know if it is true, from

Http://stackoverflow.com/questions/237104/javascript-array-containsobj

It's a very intense discussion here, and it's recommended to see if there is a way to use jquery, directly using jquery, refer to the address:

http://api.jquery.com/jQuery.inArray/

The above judge whether the array contains an element of the JS function implementation method is small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.