/** * JS to determine whether a value exists in the array * Jones Taiwan Blog */
Define a judgment function var in_array = function (arr) { Determines 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 ); Throw an exception if it is not an array 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; } }
Returns False if it is not in the array return false; }
To add a prototype to a string String.prototype.in_array = In_array; To add a prototype to a numeric type Number.prototype.in_array = In_array;
Declaring an array var arr = Array (' Blue ', ' red ', ' 110 ', ' 120 ');
String test var str = ' red '; var Isinarray = Str.in_array (arr); alert (Isinarray); True
Digital test var num = 119; var Isinarray = Num.in_array (arr); alert (Isinarray); False Throws an exception if the passed-in is not an array /** * JS to determine whether a value exists in the array * Jones Taiwan Blog */
Define a judgment function var in_array = function (arr) { Determines 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 );
Throw an exception if it is not an array 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; } }
Returns False if it is not in the array return false; } To add a prototype to a string String.prototype.in_array = In_array; To add a prototype to a numeric type Number.prototype.in_array = In_array;
Declaring 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 is a duplicate value in an array var ary = new Array ("111", "22", "33", "111"); var s = ary.join (",") + ","; for (Var i=0;i<ary.length;i++) { if (S.replace (ary[i]+ ",", ""). IndexOf (ary[i]+ ",") >-1) { Alert ("There are repeating elements in the array:" + ary[i]); Break } } |