Home >Web Front-end >JS Tutorial >javascript simulation php function in_array_javascript tips

javascript simulation php function in_array_javascript tips

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 16:02:051533browse

JS determines whether an element exists in a JS array, which is equivalent to the in_array function in the PHP language.

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)); 
}; 

Usage is as follows:

var arr=new Array(["b",2,"a",4,"test"]); 
arr.in_array('test');//判断 test 字符串是否存在于 arr 数组中,存在返回true 否则false,此处将返回true 

Note: This function is only valid for characters and numbers

There is a similar function in jQuery: http://docs.jquery.com/Utilities/jQuery.inArray

Its code is as follows:

function inArray(needle, haystack) {
  var length = haystack.length;
  for(var i = 0; i < length; i++) {
    if(haystack[i] == needle) return true;
  }
  return false;
}

The above is all the content shared with you in this article, I hope you will like it.

Statement:
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