In JS, there is no function that can be used directly to determine whether a value is in an array. For example, there is the in_array() function in PHP. But we can write a function similar to in_array() to determine whether a value is in the function
/**
* JS determines whether a value exists in an array
* Qiongtai Blog
*/
// Define a judgment function
var in_array = function(arr){
// Determine 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;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;
// Give Add prototype for numeric 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
// Numeric test
var num = 119;
var isInArray = num.in_array(arr);
alert(isInArray); // false
will be thrown if the passed in is not an array Exception occurred
/**
* 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;
}
// 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 = 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 ;
}
}