javascript simulates the php function in_array

  • 2020-06-01 08:17:32
  • OfStack

The js function, which determines whether an element exists in an js array, is equivalent to the in_array function in the php language.

  var r=new RegExp(this.S+e+this.S); 
  return (r.test(this.S+this.join(this.S)+this.S)); 

It can be used as follows:

var arr=new Array(["b",2,"a",4,"test"]); 
arr.in_array('test');// judge  test  Does the string exist in  arr  In the array, exists returns true  Otherwise, false , will be returned here true 

Note: this function is only valid for characters and Numbers

jQuery has similar function: 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;

That's all I want to share with you. I hope you like it.

Related articles: