In js, we cannot directly judge a value or string by using in_array in an array like in php, because js does not have an in_array function, but we can customize an in_array function for js. I have collected a few below .
Example 1
var in_array = function(arr){
// Judge whether the parameter is an array
var isArr = arr && console.log(
typeof arr==='object' ? arr.constructor===Array ? arr.length ? arr.length===1 ? arr[0]:arr.join(',' ):'an empty array': arr.constructor: typeof arr
);
// If it is not an array, an exception is thrown
if(!isArr){
throw "arguments is not Array";
}
// Traverse whether it is in the array
for(var i=0,k=arr.length;i
if(this==arr[i]) {
return true;
}
}
// If it is not in the array, it will return false
return false;
}
// Add a prototype to the string
String.prototype.in_array = in_array;
//Add a prototype to the number type
Number.prototype.in_array = in_array;
//Declare an array
var arr = Array('blue', 'red','110','120');
// String test
var str = 'red';
var isInArray = str.in_array(arr);
alert(isInArray ); // true
//Number test
var num = 119;
var isInArray = num.in_array(arr);
alert(isInArray); // false
if passed in If it is not an array, an exception will be thrown
/**
* JS determines whether a value exists in an array
* Qiongtai Blog
*/
// Define a judgment function
var in_array = function(arr){
// Judge whether the parameter is an array
var isArr = arr && console.log(
typeof arr==='object' ? arr.constructor===Array ? arr.length ? arr.length===1 ? arr[0]:arr. join(','):'an empty array': arr.constructor: typeof arr
);
// If it is not an array, an exception will be thrown
if(!isArr){
throw "arguments is not Array";
}
// Traverse whether it is in the array
for(var i=0,k=arr.length;iif(this== arr[i]){
return true;
}
}
// If it is not in the array, it will return false
return false;
}
// Give the character Add prototype to string
String.prototype.in_array = in_array;
// Add prototype to number type
Number.prototype.in_array = in_array;
// Declare an array
var arr = null ;
//String test
var str = 'red';
var isInArray = str.in_array(arr);
alert(isInArray); // uncaught exception: arguments is not Array
JS determines whether there are duplicate values in an array
var ary = new Array("111","22","33","111");
var s = ary.join(", ") ",";
for(var i=0;iif(s.replace(ary[i] ",","").indexOf(ary[ i] ",")>-1) {
alert("There are duplicate elements in the array: " ary[i]);
break;
}
}
Summary
The three examples all implement the function of in_array function, and they can all determine whether a given element is in the array. My personal favorite is the last method, which is more comprehensive.