Home > Web Front-end > JS Tutorial > 判断数组是否包含某个元素的js函数实现方法_javascript技巧

判断数组是否包含某个元素的js函数实现方法_javascript技巧

WBOY
Release: 2016-05-23 13:15:51
Original
1169 people have browsed it

判断数组是否包含某个元素的js函数实现方法

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

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


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

还有一个大牛是这样写的:

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));
}
Copy after login

使用方法就是 :

var arr=["a","b"];

alert(arr.in_array("a"))

据说while减迭代是js里最快的一种方法,不知道是不是真的,出自

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

这里讨论的很激烈,建议去看看,如果有使用jQuery的话,直接使用jQuery实现的方法,参考地址:

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

以上这篇判断数组是否包含某个元素的js函数实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template