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

javascript simulation php function in_array_javascript tips

WBOY
Release: 2016-05-16 16:02:05
Original
1496 people have browsed it

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

Usage is as follows:

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

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

Copy after login

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

Related labels:
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