In JS, you need to determine whether a value is in an array and is not directly used by functions. For example, in PHP, there is the function in_array(). But we can write a function similar to in_array() to determine whether it is a value in the function.
/** * JS determines whether a value exists in an array*/ // Defines a judgment function var in_array = function(arr){ // Determines whether the parameters are 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 not an array, throw an exception if(!isArr){ throw "arguments is not Array"; } // traversal is in the array for(var i=0,k=arr.length;i<k;i++){ if(this==arr[i]){ return true; } } // If not in the array, false will be returned;} // Add prototype to the string String.prototype.in_array = in_array;// Add 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); // falseIf the passed in is not an array, an exception will be thrown
/** * JS determines whether a value exists in an array*/ // Defines a judgment function var in_array = function(arr){ // Determines whether the parameters are 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 not an array, throw an exception if(!isArr){ throw "arguments is not Array"; } // traversal is in the array for(var i=0,k=arr.length;i<k;i++){ if(this==arr[i]){ return true; } } // If not in the array, false will be returned;} // Add prototype to the string String.prototype.in_array = in_array;// Add prototype to the numeric 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 ArrayDirect error: