SoFunction
Updated on 2025-04-03

JavaScript simulates php function in_array

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

=(2); 
.in_array=function(e){ 
  var r=new RegExp(+e+); 
  return ((+()+)); 
}; 

The usage is as follows:

var arr=new Array(["b",2,"a",4,"test"]); 
arr.in_array('test');//Judge whether the test string exists in the arr array, and returns true if it exists. Otherwise, false, true will be returned here

Note: This function is only valid for characters and numbers.

There are similar functions in jQuery:/Utilities/

Its code is as follows:

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

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