1. Match positive integers

// Matches positive integers
let isPositiveNum = val= > {
	return /^[1-9]\d*$/.test(val);
};
console.log(isPositiveNum(9)) //true
console.log(isPositiveNum(2.2)) //false
Copy the code

2. Match negative integers

// Matches negative integers
 let isNegativeNum = val= > {
 	return /^-[1-9]\d*$/.test(val);
 };
 console.log(isNegativeNum(9 -)) //true
 console.log(isNegativeNum(2.2)) //false
Copy the code

3. Match integers

// Matches integers
let isInteger = val= > {
	return / ^ (- | \ +)? \d+$/.test(val);
};
console.log(isInteger(9 -)) //true
console.log(isInteger(2.2)) //false
Copy the code

4. Match non-negative floating-point numbers

// Matches non-negative floating-point numbers
let isNotNegativeFloatNum = val= > {
	return /^\d+(\.\d+)? $/.test(val);
};
console.log(isNotNegativeFloatNum(9 -)) //false
console.log(isNotNegativeFloatNum(2.2)) //true
Copy the code

5. Match a string consisting of 26 letters

// Matches a string of 26 English letters
let isAZaz = val= > {
	return /^[A-Za-z]+$/.test(val);
};
console.log(isAZaz('122a')) //false
console.log(isAZaz('abc')) //true
Copy the code

6. Match a string consisting of 26 uppercase letters

// Matches a string of 26 uppercase Letters
let isAZ = val= > {
	return /^[A-Z]+$/.test(val);
};
console.log(isAZ('Acs')) //false
console.log(isAZ('ABC')) //true
Copy the code

7. Match the string consisting of 26 lowercase letters

// Matches a string of 26 lowercase letters
let isaz = val= > {
	return /^[a-z]+$/.test(val);
};
console.log(isaz('Acs')) //false
console.log(isaz('abc')) //true
Copy the code

8. Match email addresses

// Matches the email address
let isEmailAddress = val= > {
	return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(val) || /w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*/.test(val);
};
console.log(isEmailAddress('Acs')) //false
console.log(isEmailAddress('[email protected]')) //true
Copy the code

9. Return the maximum value in the array

// arrayMax: returns the maximum value in the array
// combine math.max () with the extended operator (...) Used in combination to get the maximum value in the array.
let arrayMax = arr= > Math.max(... arr);let arr = [1.2.3.5];
console.log(arrayMax(arr)) / / 5
Copy the code

10. Return the minimum value in the array

// arrayMin: Returns the minimum value in the array
// Combine math.min () with the extended operator (...) Used in combination to get the minimum value in the array.
let arrayMin = arr= > Math.min(... arr);let arr = [1.2.3.5];
console.log(arrayMin(arr)) / / 1
Copy the code

11. Divide an array block into smaller arrays of a specified size

// chunk: Divides an array block into smaller arrays of a specified size.
// Create a new Array with array.from (), which matches the number of blocks to be generated. Use array.slice () to map each element of the new Array to a size-length block. If the original array is not evenly split, the final block contains the remaining elements.
let chunk = (arr, size) = > Array.from({
	length: Math.ceil(arr.length / size)
}, (v, i) => arr.slice(i * size, i * size + size));
let arr = [1.2.3.5];
console.log(chunk(arr,2)) //0: Array [ 1, 2 ],1: Array [ 3, 5 ],
Copy the code

12. Remove false from the array

// compact: Removes false from the array.
// Filter false values (false, null, 0, "", undefined, and NaN) using array.filter ().
let compact = arr= > arr.filter(Boolean);
let arr = [false.null.0."".undefined.NaN.1]
console.log(compact(arr)) //[ 1 ]
Copy the code

13. Count the number of occurrences of values in the array

// countOccurrences: Counts the number of occurrences of values in the array
// Increments the counter each time a particular value in the Array is encountered using array.reduce ().
let countOccurrences = (arr, value) = > arr.reduce((a, v) = > v === value ? a + 1 : a + 0.0);
let arr = [1.2.1.2.3.3.3.3];
console.log(countOccurrences(arr,3))/ / 4
Copy the code

14. Deep split array

// deepFlatten: deepFlatten array
// Use recursion. Use array.concat () with empty arrays ([]) and cross-page operators (...) To splice the array. Recursively assemble each element as an array.
let deepFlatten= arr= >[].concat(... arr.map(v= > Array.isArray(v) ? deepFlatten(v) : v));
let arr = [1.2[1.2[1.2[2.3]]]];
console.log(deepFlatten(arr)) // [1, 2, 1, 2, 1, 2, 3]
Copy the code

15. Return the difference between two arrays

// difference: Returns the difference between two arrays
// Create a Set from b, then use array.filter () on to preserve only values not contained in a and b.
let difference = (a, b) = > {
	const s = new Set(b);
	return a.filter(x= >! s.has(x)); };let arr = [1.2.3];
let arr2 = [2.3.4];
console.log(difference(arr,arr2))/ / [1]
console.log(difference(arr2,arr))/ / [4]
Copy the code

Return all the different values of the array

// distinctValuesOfArray: Returns all different values of an array
// Use ES6 Set and... Rest operators discard all duplicate values.
let distinctValuesOfArray = arr= > [...new Set(arr)];
let arr = [1.2.3.1.2];
console.log(distinctValuesOfArray(arr)) // [1, 2, 3]
Copy the code

17. Return the NTH element of each array

// everyNth: returns everyNth element in the array
// Use array.filter () to create a new Array containing each NTH element of the given Array.
let everyNth = (arr, nth) = > arr.filter((e, i) = > i % nth === 0);
Copy the code

Filter out non-unique values in the array

// filterNonUnique: Filter out non-unique values in the array
// For arrays containing only unique values, use array.filter ().
let filterNonUnique = arr= > arr.filter(i= >arr.indexOf(i) ! == arr.lastIndexOf(i));Copy the code

20. Splice arrays

// flatten: splashes the array
// Use array.reduce () to get all the elements in the Array and concat() to piece them together
let flatten = arr= > arr.reduce((a, v) = > a.concat(v), []);
Copy the code

21. Assemble the array up to the specified depth

FalttenDepth: Collates the array up to the specified depth
// Use recursion, drop depth to 1 for each layer. Use array.reduce () and array.concat () to merge elements or arrays. Basically, we stop recursion for depth equal to 1. The second element is omitted, and depth is only collated to the depth of 1 (single collation).
// falttenDepth: (arr, depth = 1) => depth != 1 ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), []) : arr.reduce((a, v) => a.concat(v), []),
Copy the code

22. Group array elements according to the given function

// groupby: Groups array elements according to the given function
// Use array.map () to map the values of arrays to function or attribute names. Use array.reduce () to create an object where the keys are generated from the result of the mapping.
// groupBy: (arr, func) => arr.map(typeof func === 'function' ? func : val => val[func]).reduce((acc, val, i) => { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {}),
Copy the code

Return the head of the list

// head: Returns the head of the list
Use arr[0] to return the first element of the passed array.
let head = arr= > arr[0];
Copy the code

24. Return all elements except the last array

// initial: returns all elements except the last array
Slice (0,-1) returns the last element of the array with "arr.slice(0,-1)".
let initial = arr= > arr.slice(0.- 1);
Copy the code

Initialize and populate an array with the specified value

/ / initializeArrayWithRange: initialization and filled with a specified value of the array
// Create an Array of the required length using Array(n),fill(v) to fill the required values. You can omit value to use the default value 0.
let initializeArrayWithRange = (end, start = 0) = > Array.from({
	length: end - start
}).map((v, i) = > i + start);
Copy the code

26. Initialize and populate an array with the specified value

/ / initializeArrayWithValues: initialization and filled with a specified value of the array
// Create an Array of the required length using Array(n),fill(v) to fill the required values. You can omit value to use the default value 0
let initializeArrayWithValues = (n, value = 0) = > Array(n).fill(value);
Copy the code

27. Return a list of elements that exist in both arrays

// intersection: Returns the list of elements that exist in two arrays
// Create a Set from b, then use array.filter ()on a to preserve only the values contained in b.
let intersection = (a, b) = > {
	const s = new Set(b);
	return a.filter(x= > s.has(x));
};
Copy the code

Return the last element in the array

// last: Returns the last element in the array
Arr. Length-1 computs the index of the last element of a given array and returns it
let last = arr= > arr[arr.length - 1];
Copy the code

29. Use functions to map the values of an array to an object, where key-value pairs consist of primitive values as keys and mapped values

// mapObject: Uses functions to map the values of an array to an object, where key-value pairs consist of raw values as keys and mapped values
// Use anonymous internal function scopes to declare undefined memory space, and use closures to store return values. Using the new Array puts the mapping of that Array to a function on its data set, and the comma operator returns the second step without needing to move from one context to another (due to closure and operation order).
let mapObject = (arr, fn) = > (a= > (a = [arr, arr.map(fn)], a[0].reduce((acc, val, ind) = > (acc[val] = a[1][ind], acc), {})))
	();
Copy the code

30. NthElement: returns the nthElement of the array

// nthElement: returns the nthElement of the array
// Use array.slice () to get an Array containing the NTH element. If the index is out of bounds, return []. Omit the second argument n to get the first element of the array
let nthElement = (arr, n = 0) = > (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
Copy the code

31. Select a key-value pair from the object that corresponds to the given key

// pick: Selects the key-value pair corresponding to the given key from the object
// Use array.reduce () to convert the filtered/selected key back to an object with the corresponding key-value pair (if it exists in obj).
let pick = (obj, arr) = > arr.reduce((acc, curr) = > (curr in obj && (acc[curr] = obj[curr]), acc), {});
Copy the code

32. Mutate the original array to filter out the specified value

// pull: Mutates the original array to filter out the specified value
// Use array.filter () and array.includes () to pull out unwanted values. Using array.length = 0 resets the length in the passed Array to zero and sets it to array.push () to populate it with only the extracted values.
let pull = (arr, ... args) = > {
	let pulled = arr.filter((v, i) = >! args.includes(v)); arr.length =0;
	pulled.forEach(v= > arr.push(v));
};
Copy the code

33. Remove the element from the array where the given function returns false

// remove: Removes the element from the array that the given function returns false
// Use array.filter () to find Array elements that return truthy values and array.reduce () to remove elements using array.splice (). Use three arguments (func value, index, array to call the function).
let remove = (arr, func) = > Array.isArray(arr) ? arr.filter(func).reduce((acc, val) = > {
	arr.splice(arr.indexOf(val), 1);
	returnacc.concat(val); } []) : [];Copy the code

34. Return a random element in an array

// sample: Returns a random element in the array
// Use math.random () to generate a random number, multiply it by length, and use mathematics to round it to the nearest integer math.floor (). This method also works with strings
let sample = arr= > arr[Math.floor(Math.random() * arr.length)];
Copy the code

35. Order of random group values

// shuffle: Specifies the sequence of random number group values
// Use array.sort () to reorder elements in the comparator using math.random ().
let shuffle = arr= > arr.sort((a)= > Math.random() - 0.5);
Copy the code

36. Returns an array of elements displayed in both arrays

// similarity: Returns an array of elements displayed in both arrays
// Use filter() to delete values that do not belong to values. Use includes() to determine.
let similarity = (arr, values) = > arr.filter(v= > values.includes(v));
Copy the code

Return the symmetry difference between two arrays

// symmetricDifference: Returns the symmetry difference between two arrays
// Create a Set from each Array, and then use array.filter () for each of them to preserve only values not contained in the other values.
let symmetricDifference = (a, b) = > {
	const sA = new Set(a),
		sB = new Set(b);
	return [...a.filter(x= >! sB.has(x)), ... b.filter(x= >! sA.has(x))]; };Copy the code

38. Return all elements in the array except the first

// tail: Returns all elements in the array except the first
Arr.slice (1) is returned if the array length is greater than 1, otherwise the entire array is returned.
let tail = arr= > arr.length > 1 ? arr.slice(1) : arr;
Copy the code

39. Return an array with n elements removed from the start

// take: Returns an array with n elements removed from the beginning
// Use array.slice () to create a slice of the Array containing the n elements taken from the beginning
let take = (arr, n = 1) = > arr.slice(0, n);
Copy the code

40. Return an array with n elements removed from the end

// takeRight: Returns an array with n elements removed from the end
// Use array.slice () to create a slice of the Array containing the n element fetched from the end
let takeRight = (arr, n = 1) = > arr.slice(arr.length - n, arr.length);
Copy the code

41. Return each element that exists in either array

// union: Returns each element that exists in either array
// Create a Set containing all the values of a and b and convert them to an array.
let union = (a, b) = > Array.from(new Set([...a, ...b]));
Copy the code

Filter out the element in the array with one of the specified values

// without: Filter out the element in the array with one of the specified values
// Use array.filter () to create an Array that is not included (use! Array.includes()) all the given values.
let without = (arr, ... args) = > arr.filter(v= >! args.includes(v));Copy the code

43. Create an array of elements grouped based on positions in the original array

Zip: creates an array of elements grouped based on positions in the original array
// Use math.max.apply () to get the longest array of parameters. Create an Array with that length as the return value, and use the map function to create an Array of grouped elements array.from (). If the Array of parameters has different lengths, use undefined if no value is found.
let zip = (. arrays) = > {
	const maxLength = Math.max(... arrays.map(x= > x.length));
	return Array.from({
		length: maxLength
	}).map((_, i) = > {
		return Array.from({
			length: arrays.length }, (_, k) => arrays[k][i]); })};Copy the code

44. Removes an item from the given array

// Removes an item from the given array
let removeArrayItem = function(arr, item) {
	var i = 0;
	while (i < arr.length) {
		if (arr[i] == item) {
			arr.splice(i, 1);
		} else{ i++; }}return arr;
};
Copy the code

45. Check whether a given array contains an item

// Check whether the given array contains an item
let contains = function(arr, item) {
	var i = arr.length;
	while (i--) {
		if (arr[i] === item) {
			return true; }}return false;
};
Copy the code

46. Validation cannot contain letters

 /** * @param { string } value */
 export const isNoWord = value= > /^[^A-Za-z]*$/g.test(value);
Copy the code

47. Verify Chinese and numbers

/**
@param { string } value
*/
export const isCHNAndEN = value= >/ ^ ((? :[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\u D86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD 86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])|(\d))+$/g.test(value);Copy the code

48. Verify zip Code (China)

/**
@param { string } value
*/
export const isPostcode = value= >/ ^ (0[17 -] |1[0- 356.] |2[07 -] |3[0- 6] |4[07 -] |5[17 -] |6[17 -] |7[0- 5] |8[013- 6])\d{4}$/g.test(value);
Copy the code

49. Verify wechat id, 6 to 20 characters, beginning with a letter, letter, number, minus sign, underscore

/**
@param { string } value
*/
export const isWeChatNum = value= > /^[a-zA-Z][-_a-zA-Z09 -] {5.19}$/g.test(value);
Copy the code

50. Verify hexadecimal colors

/** @param { string } value */ export const isColor16 = value => /^#? ([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/g.test(value);Copy the code

51. Verify the train number

/**
@param { string } value
*/
export const isTrainNum = value= > /^[GCDZTSPKXLY19 -]\d{1.4}$/g.test(value);
Copy the code

52. Verify the phone body code (IMEI)

/**
@param { string } value
*/
export const isIMEI = value= > /^\d{15.17}$/g.test(value);
Copy the code

53. Verify url (or IP) that must have port number

/**
@param { string } value
*/
export const isHttpAndPort = value= >/^((ht|f)tps? : \ \ /)? [\w-]+(\.[\w-]+)+:\d{1.5} \ /? $/g.test(value);Copy the code

54. Verify url (support port and “? + parameter “and “#+ parameter)

/**
@param { string } value
*/
export const isRightWebsite = value= >/^(((ht|f)tps?) : \ \ /)? [\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])? $/g.test(value);
Copy the code

55. Verify the Universal Social Credit code

/**
@param { string } value
*/
export const isCreditCode = value= >/ ^ [09 -A-HJ-NPQRTUWXY]{2}\d{6} [09 -A-HJ-NPQRTUWXY]{10}$/g.test(value);
Copy the code

56. Verify the Thunderbolt link

/**
@param { string } value
*/
export const isThunderLink = value= >/^thunderx? :\/\/[a-zA-Z\d]+=$/g.test(value);Copy the code

57. Verify ED2K links (loose matching)

/**
@param { string } value
*/
export const ised2k = value= > /^ed2k:\/\/\|file\|.+\|\/$/g.test(value);
Copy the code

58. Verify magnetic links (loose matching)

/**
@param { string } value
*/
export const isMagnet = value= >/^magnet:\? xt=urn:btih:[09 -a-fA-F]{40,}.*$/g.test(value);
Copy the code

59. Verify the subnet mask

/**
@param { string } value
*/
export const isSubnetMask = value= >/ ^ (? :\d{1.2} |1\d\d|2[04 -]\d|25[0- 5(])? : \. (? :\d{1.2} |1\d\d|2[04 -]\d|25[0- 5])){3}$/g.test(value);
Copy the code

60. Verify the Linux folder path

/**
@param { string } value
*/
export const isLinuxFolderPath = value= >/ ^ (\ [^+ / / /] +)? $/g.test(value);
Copy the code

Verify the Linux “file” path

/**
@param { string } value
*/
export const isLinuxFilePath = value= >/ ^ (\ [^/]+)+$/g.test(value);
Copy the code

62. Verify the window” folder “path

/**
@param { string } value
*/
export const isWindowsFolderPath = value= >/^[a-zA-Z]:\\(? :\w+\\?) *$/g.test(value);Copy the code

63. Verify the “File” path under Window

/**
@param { string } value
*/
export const isWindowsFilePath = value= >/^[a-zA-Z]:\\(? :\w+\\)*\w+\.\w+$/g.test(value);Copy the code

64. Verify stock code (A-share)

/**
@param { string } value
*/
export const isAShare = value= > /^(s[hz]|S[HZ])(000[\d]{3} |002[\d]{3} |300[\d]{3} |600[\d]{3} |60[\d]{4})$/g.test(value);
Copy the code

65. The verification version must be in X.Y.Z format

/**
@param { string } value
*/
export const isVersion = value= >/^\d+(? :\.\d+){2}$/g.test(value);
Copy the code

66. Verify the video link address (video format can be added or deleted as required)

/**
@param { string } value
*/
export const isVideoUrl = value= >/^https? :\/\/(.+\/)+.+(\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4))$/i.test(value);
Copy the code

67. Verify the image link address (image format can be added or deleted as required)

/**
@param { string } value
*/
export const isImageUrl = value= >/^https? :\/\/(.+\/)+.+(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i.test(value);Copy the code

68. Verify bank card number (10 to 30 digits, covering public and private accounts, refer to wechat Pay)

/**
@param { string } value
*/
export const isAccountNumber = value= >/ ^ [19 -]\d{9.29}$/g.test(value);
Copy the code

69. Verify Chinese names

/**
@param { string } value
*/
export const isChineseName = value= >/ ^ (? "[the] \ u4e00 - \ u9fa5 {2.16})$/g.test(value);
Copy the code

70. Verify English names

/**
@param { string } value
*/
export const isEnglishName = value= > /(^[a-zA-Z]{1}[a-zA-Z\s]{0.20}[a-zA-Z]{1}$)/g.test(value);
Copy the code

71. Verification of license plate number (new energy)

/**
@param { string } value
*/
export const isLicensePlateNumberNER = value= >/[Beijing, Tianjin, Shanghai, Chongqing, Hebei, Yun, Liao, Heixiang, Anhui, Lu, Xinsu, Zhejiang, Hubei, GUI, Gan, Jin, Mengshan, Shaanxi, Ji, Min, GUI, Guangdong, Qinghai, Sichuan, Ning, Qiong, ling, A-z]{1}[A-HJ-NP-Z]{1} (((09 -] {5}[DF])|([DF][A-HJ-NP-Z09 -] [09 -] {4}))$/g.test(value);
Copy the code

72. Verify license plate number (non-new energy)

/**
@param { string } value
*/
export const isLicensePlateNumberNNER = value= >/^[Beijing, Tianjin, Shanghai, Chongqing, Hebei, Yunyun, Liao, Heixiang, Anhui, Lu, Xinsu, Zhejiang, Hubei, Guigan, Jin, Mengshan, Ji, Min, Guiyue]{1}[A-HJ-NP-Z]{1}[A-Z09 -] {4}[A-Z09 -Hang student police Hong Kong and Macau]{1}$/g.test(value);
Copy the code

73. Verify license plate number (new energy + non-new energy)

/**
@param { string } value
*/
export const isLicensePlateNumber = value= >/ ^ (? : Beijing, Tianjin, Shanghai, Chongqing, Hebei, Yun, Liao, Heixiang, Anhui, Lu, Xinsu, Zhejiang, Gan, Hubei, GUI, Jin, Mengshan, Shaanxi, Ji, Min, GUI, Guangdong, Qinghai, Tibet, Sichuan, Ning, Qiong, Ling, A-z1}[A-HJ-NP-Z]{1} (? : (? : [09 -] {5}[DF])|(? :[DF](? :[A-HJ-NP-Z09 -[])09 -] {4}))) | (? : Beijing, Tianjin, Shanghai, Chongqing, Hebei, Yun, Liao, Heixiang, Anhui, Lu, Xinsu, Zhejiang, Gan, Hubei, GUI, Jin, Mengshan, Shaanxi, Ji, Min, GUI, Guangdong, Qinghai, Tibet, Sichuan, Ning, Qiong, Ling, A-z1}[A-Z]{1}[A-HJ-NP-Z09 -] {4}[A-HJ-NP-Z09 -Hang student police Hong Kong and Macau]{1})$/g.test(value);
Copy the code

74. Verify mobile phone number China (rigorous), according to the latest mobile phone number segment released by the Ministry of Industry and Information Technology in 2019

/**
@param { string } value
*/
export const isMPStrict = value= >/ ^ (? : (? : \ + |00)86)?1(? : (? :3[\d])|(? :4[57 -|9]) | (? :5[0- 3|59 -]) | (? :6[57 -]) | (? :7[0- 8 -]) | (? :8[\d])|(? :9[1|8|9]))\d{8}$/g.test(value);
Copy the code

75. Verify the mobile phone number China (loose), as long as it starts with 13,14,15,16,17,18,19

/**
@param { string } value
*/
export const isMPRelaxed = value= >/ ^ (? : (? : \ + |00)86)?1[39 -]\d{9}$/g.test(value);
Copy the code

76. Verify email

/** @param { string } value */ export const isEmail = value => /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](? : [a - zA - Z0-9 -], 21 {0} [a zA - Z0-9])? (? :\.[a-zA-Z0-9](? : [a - zA - Z0-9 -], 21 {0} [a zA - Z0-9])?) *$/g.test(value);Copy the code

77. Verify the landline number (domestic), for example: 0341-86091234

/**
@param { string } value
*/
export const isLandlineTelephone = value= > /\d{3}-\d{8}|\d{4}-\d{7}/g.test(value);
Copy the code

78. Verify ID number (1 generation,15 digits)

/**
@param { string } value
*/
export const isIDCardOld = value= > /^\d{8} (0\d|10|11|12) ([02 -]\d|30|31)\d{3}$/g.test(value);
Copy the code

79. Verify the ID number (2 generations,18 digits) with the last digit being the check bit, which may be a number or character X

/**
@param { string } value
*/
export const isIDCardNew = value= > /^\d{6} (18|19|20)\d{2} (0\d|10|11|12) ([02 -]\d|30|31)\d{3}[\dXx]$/g.test(value);
Copy the code

80. Verify ID number, support 1/2 generation (15 /18 digits)

/**
@param { string } value
*/
export const isIDCard = value= > /(^\d{8} (0\d|10|11|12) ([02 -]\d|30|31)\d{3}$)|(^\d{6} (18|19|20)\d{2} (0\d|10|11|12) ([02 -]\d|30|31)\d{3}(\d|X|x)$)/g.test(value);
Copy the code

81. Passport verification (including Hong Kong and Macao)

/**
@param { string } value
*/
export const isPassport = value= > /(^[EeKkGgDdSsPpHh]\d{8}$)|(^(([Ee][a-fA-F])|([DdSsPp][Ee])|([Kk][Jj])|([Mm][Aa])|(1[45]))\d{7}$)/g.test(value);
Copy the code

82. Verify that the account is valid (starts with a letter, allows 5-16 bytes, alphanumeric underscore (_)

/**
@param { string } value
*/
export const isWebAccount = value= > /^[a-zA-Z]\w{4.15}$/g.test(value);
Copy the code

83. Verify Chinese/Chinese characters

/**
@param { string } value
*/
export const isChineseCharacter = value= >/ ^ (? :[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\u D86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD 86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])+$/g.test(value);Copy the code

84. Verify decimals

/**
@param { string } value
*/
export const isDecimal = value= > /^\d+\.\d+$/g.test(value);
Copy the code

85. Verify the numbers

/**
@param { string } value
*/
export const isNumber = value= > /^\d{1,}$/g.test(value);
Copy the code

86. Verify the qq id format

/**
@param { string } value
*/
export const isQQNum = value= >/ ^ [19 -] [09 -] {4.10}$/g.test(value);
Copy the code

87. Verify number and letter composition

/**
@param { string } value
*/
export const isNumAndStr = value= > /^[A-Za-z09 -]+$/g.test(value);
Copy the code

88. Verify English letters

/**
@param { string } value
*/
export const isEnglish = value= > /^[a-zA-Z]+$/g.test(value);
Copy the code

89. Verify capital Letters

/**
@param { string } value
*/
export const isCapital = value= > /^[A-Z]+$/g.test(value);
Copy the code

90. Verify lowercase Letters

/**
@param { string } value
*/
export const isLowercase = value= > /^[a-z]+$/g.test(value);
Copy the code

Browser operation related browser tool functions

Return the current URL

export const currentURL = (a)= > window.location.href;
Copy the code

92. Get URL parameters (type 1)

/** * @param {*} name * @param {*} origin */
export function getUrlParam(name, origin = null) {
    let reg = new RegExp("(^ | &)" + name + "= (/ ^ & *) (& | $)");
    let r = null;
    if (origin == null) {
        r = window.location.search.substr(1).match(reg);
    } else {
        r = origin.substr(1).match(reg);
    }
    if(r ! =null) return decodeURIComponent(r[2]);
    return null;
}
Copy the code

93. Get URL parameters (second kind)

 /** * @param {*} name * @param {*} origin */
       export function getUrlParams(name, origin = null) {
       let url = location.href;
       let temp1 = url.split('? ');
       let pram = temp1[1];
       let keyValue = pram.split('&');
       let obj = {};
       for (let i = 0; i < keyValue.length; i++) {
           let item = keyValue[i].split('=');
       let key = item[0];
        let value = item[1];
        obj[key] = value;
    }
    return obj[name];
 
    }
Copy the code

94. Modify parameters in the URL

 /** * @param { string } paramName * @param { string } replaceWith */
       export function replaceParamVal(paramName,replaceWith) {
   var oUrl = location.href.toString();
    var re=eval('/'+ paramName+'=)([^&]*)/gi');
    location.href = oUrl.replace(re,paramName+'='+replaceWith);
    return location.href;
    }
Copy the code

95. Delete parameters specified in the URL

 /** * @param { string } name */
       export function funcUrlDel(name){
       var loca =location;
       var baseUrl = loca.origin + loca.pathname + "?";
       var query = loca.search.substr(1);
       if (query.indexOf(name)>- 1) {
           var obj = {};
           var arr = query.split("&");
           for (var i = 0; i < arr.length; i++) {
               arr[i] = arr[i].split("=");
               obj[arr[i][0]] = arr[i][1];
           }
           delete obj[name];
       var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g."").replace(/\:/g."=").replace(/\,/g."&");
        return url
    }
    }
Copy the code

96. Get the height of the window’s viewable range

export function getClientHeight() {
    let clientHeight = 0;
    if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    }
    else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    }
    return clientHeight;
}
Copy the code

Get window viewable range width

export function getPageViewWidth() {
    let d = document,
        a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
    return a.clientWidth;
}
Copy the code

98. Get the window width

export function getPageWidth() {
    let g = document,
        a = g.body,
        f = g.documentElement,
        d = g.compatMode == "BackCompat" ? a : g.documentElement;
    return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth);
}
Copy the code

99. Get the window size

export function getViewportOffset() {
    if (window.innerWidth) {
        return {
            w: window.innerWidth,
            h: window.innerHeight
        }
    } else {
        // Ie8 and below
        if (document.compatMode === "BackCompat") {
            // Weird mode
            return {
                w: document.body.clientWidth,
                h: document.body.clientHeight
            }
        } else {
            // Standard mode
            return {
                w: document.documentElement.clientWidth,
                h: document.documentElement.clientHeight
            }
        }
    }
}
Copy the code

100. Gets the scrollbar height from the top

export function getPageScrollTop() {
    let a = document;
    return a.documentElement.scrollTop || a.body.scrollTop;
}
Copy the code

Gets the height to the left of the scrollbar pitch

export function getPageScrollLeft() {
    let a = document;
    return a.documentElement.scrollLeft || a.body.scrollLeft;
}
Copy the code

102. Enable full screen

 /** * @param {*} element */
       export function launchFullscreen(element) {
       if (element.requestFullscreen) {
           element.requestFullscreen()
       } else if (element.mozRequestFullScreen) {
           element.mozRequestFullScreen()
       } else if (element.msRequestFullscreen) {
           element.msRequestFullscreen()
   } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullScreen()
    }
    }
Copy the code

103. Turn off full screen

export function exitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen()
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
    }
}
Copy the code

104. Returns the current scrollbar position

export const getScrollPosition = (el = window) = > ({
    x: el.pageXOffset ! = =undefined ? el.pageXOffset : el.scrollLeft,
    y: el.pageYOffset ! = =undefined ? el.pageYOffset : el.scrollTop
});
Copy the code

105. Scroll to the specified element area

export const smoothScroll = element= >{
    document.querySelector(element).scrollIntoView({
        behavior: 'smooth'
    });
};
Copy the code

Scroll smoothly to the top of the page

export const scrollToTop = (a)= > {
    const c = document.documentElement.scrollTop || document.body.scrollTop;
    if (c > 0) {
        window.requestAnimationFrame(scrollToTop);
        window.scrollTo(0, c - c / 8); }};Copy the code

107. The HTTP jump HTTPS

export const httpsRedirect = (a)= > {
    if(location.protocol ! = ='https:') location.replace('https://' + location.href.split('/ /') [1]);
};
Copy the code

108. Check whether the bottom of the page is visible

export const bottomVisible = (a)= >{
    return document.documentElement.clientHeight + window.scrollY >=
        (document.documentElement.scrollHeight || document.documentElement.clientHeight);
};
Copy the code

109. Open a window

 /** * @param { string } url * @param { string } windowName * @param { number } width * @param { number } height */
       export function openWindow(url, windowName, width, height) {
       var x = parseInt(screen.width / 2.0) - width / 2.0;
       var y = parseInt(screen.height / 2.0) - height / 2.0;
       var isMSIE = navigator.appName == "Microsoft Internet Explorer";
       if (isMSIE) {
           var p = "resizable=1,location=no,scrollbars=no,width=";
           p = p + width;
           p = p + ",height=";
           p = p + height;
           p = p + ",left=";
           p = p + x;
           p = p + ",top=";
           p = p + y;
           window.open(url, windowName, p);
       } else {
           var win = window.open(
               url,
               "ZyiisPopup"."top=" +
               y +
               ",left=" +
               x +
               ",scrollbars=" +
               scrollbars +
               ",dialog=yes,modal=yes,width=" +
               width +
               ",height=" +
           height +
            ",resizable=no"
        );
        eval("try { win.resizeTo(width, height); } catch(e) { }"); win.focus(); }}Copy the code

110. Adaptive Pages (REM)

 /** * @param { number } width */
       export function AutoResponse(width = 750) {
       const target = document.documentElement;
   target.clientWidth >= 600
        ? (target.style.fontSize = "80px")
        : (target.style.fontSize = target.clientWidth / width * 100 + "px");
    }
Copy the code

Date tool Date Tool function

111. Browser storage related storage utility functions

Mainly for the browser storage aspects of the utility functions, most of the transport of the Big Fire Wolf 1

112. LocalStorage storage

 @param {String} key * @param {String} value */
    export const localStorageSet = (key, value) = > {
    if (typeof (value) === 'object') value = JSON.stringify(value);
    localStorage.setItem(key, value)
    };
Copy the code

113. The localStorage

 /** * @param {String} key attribute */
    export const localStorageGet = (key) = > {
    return localStorage.getItem(key)
    };
Copy the code

114. The localStorage removed

 /** * @param {String} key attribute */
    export const localStorageRemove = (key) = > {
    localStorage.removeItem(key)
    };
Copy the code

115. LocalStorage storage expires for a certain period of time

 /** * @param {String} key attribute * @param {*} value Storage value * @param {number} expire time, milliseconds */
       export const localStorageSetExpire = (key, value, expire) = > {
   if (typeof (value) === 'object') value = JSON.stringify(value);
    localStorage.setItem(key, value);
    setTimeout((a)= > {
        localStorage.removeItem(key)
    }, expire)
    };
Copy the code

116. The sessionStorage storage

 /** * @param {String} key attribute * @param {*} value Value */
    export const sessionStorageSet = (key, value) = > {
    if (typeof (value) === 'object') value = JSON.stringify(value);
    sessionStorage.setItem(key, value)
    };
Copy the code

117. The sessionStorage

 /** * @param {String} key attribute */
    export const sessionStorageGet = (key) = > {
    return sessionStorage.getItem(key)
    };
Copy the code

118. Delete sessionStorage

 /** * @param {String} key attribute */
    export const sessionStorageRemove = (key) = > {
    sessionStorage.removeItem(key)
    };
Copy the code

SessionStorage expires for a certain period of time

 /** * @param {String} key attribute * @param {*} value Storage value * @param {String} expire time, milliseconds */
       export const sessionStorageSetExpire = (key, value, expire) = > {
   if (typeof (value) === 'object') value = JSON.stringify(value);
    sessionStorage.setItem(key, value);
    setTimeout((a)= > {
        sessionStorage.removeItem(key)
    }, expire)
    };
Copy the code

120. The cookie store

 /** * @param {String} key attribute * @param {*} value value * @param {String} expire time, in days */
    export const cookieSet = (key, value, expire) = > {
    const d = new Date(a); d.setDate(d.getDate() + expire);document.cookie = `${key}=${value}; expires=${d.toUTCString()}`
    };
Copy the code

121. The cookie

 /** * @param {String} key attribute */
       export const cookieGet = (key) = > {
       const cookieStr = unescape(document.cookie);
       const arr = cookieStr.split('; ');
       let cookieValue = ' ';
       for (let i = 0; i < arr.length; i++) {
           const temp = arr[i].split('=');
           if (temp[0] === key) {
               cookieValue = temp[1];
               break}}return cookieValue
    };
Copy the code

122. Cookies are deleted

 /** * @param {String} key attribute */
    export const cookieRemove = (key) = > {
    document.cookie = `The ${encodeURIComponent(key)}=; expires=The ${new Date()}`
    };
Copy the code

123. More utility functions

This contains the usual utility functions, including numbers, strings, arrays, objects and so on.

124. Money format, three digits plus comma

/** * @param { number } num */
    export const formatMoney = num= > num.toString().replace(/\B(? =(\d{3})+(? ! \d))/g.",");
Copy the code

125. Cut the string and omit it

export function subText(str, length) {
    if (str.length === 0) {
        return ' ';
    }
    if (str.length > length) {
        return str.substr(0, length) + "...";
    } else {
        returnstr; }}Copy the code

126. Get the base64 encoding of the file

 /** * @param file * @param format Specifies the file format * @param size specifies the file size (bytes) * @param formatMsg format error message * @param sizeMsg size out of limit message * @returns {Promise
      
       } */
      
       export function fileToBase64String(file, format = ['jpg'.'jpeg'.'png'.'gif'], size = 20 * 1024 * 1024, formatMsg = 'File format is incorrect', sizeMsg = 'File size out of limit') {
       return new Promise((resolve, reject) = > {
           // Format filtering
           let suffix = file.type.split('/') [1].toLowerCase();
           let inFormat = false;
           for (let i = 0; i < format.length; i++) {
               if (suffix === format[i]) {
                   inFormat = true;
                   break; }}if(! inFormat) { reject(formatMsg); }// Size filter
           if (file.size > size) {
               reject(sizeMsg);
           }
           // Turn base64 to a character string
       let fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onload = (a)= > {
            let res = fileReader.result;
            resolve({base64String: res, suffix: suffix});
            reject('Abnormal file, please reselect'); }})}Copy the code

127.B converts to KB,MB,GB and keeps two decimal places

 /** * @param { number } fileSize */
       export function formatFileSize(fileSize) {
       let temp;
       if (fileSize < 1024) {
           return fileSize + 'B';
       } else if (fileSize < (1024 * 1024)) {
           temp = fileSize / 1024;
           temp = temp.toFixed(2);
           return temp + 'KB';
       } else if (fileSize < (1024 * 1024 * 1024)) {
           temp = fileSize / (1024 * 1024);
           temp = temp.toFixed(2);
           return temp + 'MB';
       } else {
           temp = fileSize / (1024 * 1024 * 1024);
       temp = temp.toFixed(2);
        return temp + 'GB'; }}Copy the code

128. The base64 file

 /** * @param {base64} base64 * @param {string} filename specifies the converted filename */
        export const base64ToFile = (base64, filename ) = > {
        let arr = base64.split(', ');
        let mime = arr[0].match(/ : (. *?) ; /) [1];
        let suffix = mime.split('/') [1];// Image suffix
        let bstr = atob(arr[1]);
        let n = bstr.length;
        let u8arr = new Uint8Array(n);
    while (n--) {
         u8arr[n] = bstr.charCodeAt(n)
     }
     return new File([u8arr], `${filename}.${suffix}`, { type: mime })
     };
Copy the code

129. The base64 blob

/** * @param { base64 } base64 */
       export const base64ToBlob = base64= > {
       let arr = base64.split(', '),
           mime = arr[0].match(/ : (. *?) ; /) [1],
           bstr = atob(arr[1]),
           n = bstr.length,
           u8arr = new Uint8Array(n);
       while (n--) {
       u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
    };
Copy the code

130. Turn the file blob

/** * @param { blob } blob * @param { string } fileName */
   export const blobToFile = (blob, fileName) = > {
    blob.lastModifiedDate = new Date(a); blob.name = fileName;return blob;
    };
Copy the code

131. The file transfer base64

 /** * @param {*} file File */
       export const fileToBase64 = file= > {
       let reader = new FileReader();
       reader.readAsDataURL(file);
   reader.onload = function (e) {
        return e.target.result
    };
    };
Copy the code

132. Recursively generate tree structure

export function getTreeData(data, pid, pidName = 'parentId', idName = 'id', childrenName = 'children', key) {
    let arr = [];

    for (let i = 0; i < data.length; i++) {
        if(data[i][pidName] == pid) { data[i].key = data[i][idName]; data[i][childrenName] = getTreeData(data, data[i][idName], pidName, idName, childrenName); arr.push(data[i]); }}return arr;

}
Copy the code

133. Traverse the tree node

export function foreachTree(data, childrenName = 'children', callback) {
    for (let i = 0; i < data.length; i++) {
        callback(data[i]);
        if (data[i][childrenName] && data[i][childrenName].length > 0) { foreachTree(data[i][childrenName], childrenName, callback); }}}Copy the code

134. Trace the parent node

export function traceParentNode(pid, data, rootPid, pidName = 'parentId', idName = 'id', childrenName = 'children') {
    let arr = [];
    foreachTree(data, childrenName, (node) => {
        if (node[idName] == pid) {
            arr.push(node);
            if(node[pidName] ! = rootPid) { arr = arr.concat(traceParentNode(node[pidName], data, rootPid, pidName, idName)); }}});return arr; 
}
Copy the code

135. Find all child nodes

export function traceChildNode(id, data, pidName = 'parentId', idName = 'id', childrenName = 'children') {
    let arr = [];
    foreachTree(data, childrenName, (node) => {
        if(node[pidName] == id) { arr.push(node); arr = arr.concat(traceChildNode(node[idName], data, pidName, idName, childrenName)); }});return arr;
}
Copy the code

136. Generate tree structure according to PID

/** * @param {object} items Data obtained in the background * @param {*} ID ID in the data * @param {*} link Basis for generating the tree structure */
    export const createTree = (items, id = null, link = 'pid') = >{
    items.filter(item= > item[link] === id).map(item= > ({ ...item, children: createTree(items, item.id) }));
    };
Copy the code

137. Queries for the presence of an element in an array and returns the element’s first occurrence index

 /** * @param {*} item * @param { array } data */
       export function inArray(item, data) {
       for (let i = 0; i < data.length; i++) {
           if (item === data[i]) {
           returni; }}return - 1;
    }
Copy the code

138.Windows determines the current system name based on the detailed version number

 /** * @param { string } osVersion */
       export function OutOsName(osVersion) {
       if(! osVersion){return
       }
       let str = osVersion.substr(0.3);
       if (str === "5.0") {
           return "Win 2000"
       } else if (str === "5.1") {
           return "Win XP"
       } else if (str === "5.2") {
           return "Win XP64"
       } else if (str === "6.0") {
           return "Win Vista"
       } else if (str === "6.1") {
           return "Win 7"
       } else if (str === "6.2") {
           return "Win 8"
       } else if (str === "6.3") {
           return "Win 8.1"
       } else if (str === "10.") {
           return "Win 10"
   } else {
        return "Win"}}Copy the code

139. Determine whether your phone is Android or IOS

/** * 0: ios * 1: Android * 2: other */
       export function getOSType() {
       let u = navigator.userAgent, app = navigator.appVersion;
       let isAndroid = u.indexOf('Android') > - 1 || u.indexOf('Linux') > - 1;
       letisIOS = !! u.match(/\(i[^;] +; ( U;) ? CPU.+Mac OS X/);
       if (isIOS) {
           return 0;
   }
    if (isAndroid) {
        return 1;
    }
    return 2;
    }
Copy the code

140. Function stabilization

 /** * @param {function} func * @param {number} wait number of milliseconds * @param {Boolean} immediate true False The table does not execute */ immediately
       export function debounce(func,wait,immediate) {
       let timeout;
       return function () {
           let context = this;
           let args = arguments;
    
           if (timeout) clearTimeout(timeout);
           if (immediate) {
               letcallNow = ! timeout; timeout = setTimeout((a)= > {
                   timeout = null;
               }, wait);
               if (callNow) func.apply(context, args)
       }
        else {
            timeout = setTimeout((a)= >{ func.apply(context, args) }, wait); }}}Copy the code

145. Function throttling

 /** * @param {function} func function * @param {number} wait number of milliseconds * @param {number} type 1 table timestamp version, 2 table timer version */
       export function throttle(func, wait ,type) {
       let previous, timeout;
       if(type===1){
           previous = 0;
       }else if(type===2){
       timeout = null;
       }
       return function() {
           let context = this;
           let args = arguments;
           if(type===1) {let now = Date.now();
    
               if(now - previous > wait) { func.apply(context, args); previous = now; }}else if(type===2) {if(! timeout) { timeout = setTimeout((a)= > {
                   timeout = null;
                    func.apply(context, args)
                }, wait)
            }
        }
 
    }
    }
Copy the code

146. Determine the data type

 /** * @param {*} target */
       export function type(target) {
       let ret = typeof(target);
       let template = {
           "[object Array]": "array"."[object Object]":"object"."[object Number]":"number - object"."[object Boolean]":"boolean - object"."[object String]":'string-object'
       };
    
       if(target === null) {
           return 'null';
       }else if(ret == "object") {let str = Object.prototype.toString.call(target);
           return template[str];
   }else{
        returnret; }}Copy the code

Generates a specified range of random numbers

 /** * @param { number } min * @param { number } max */
    export const RandomNum = (min, max) = > Math.floor(Math.random() * (max - min + 1)) + min;
Copy the code

148. Array out of order

 /** * @param {array} arr */
       export function arrScrambling(arr) {
       let array = arr;
       let index = array.length;
       while (index) {
           index -= 1;
           let randomIndex = Math.floor(Math.random() * index);
           let middleware = array[index];
           array[index] = array[randomIndex];
       array[randomIndex] = middleware
    }
    return array
    }
Copy the code

150. Array intersection

 /** * @param { array} arr1 * @param { array } arr2 */
    export const similarity = (arr1, arr2) = > arr1.filter(v= > arr2.includes(v));
Copy the code

151. The number of occurrences of an element in an array

 /** * @param { array } arr * @param {*} value */
    export function countOccurrences(arr, value) {
    return arr.reduce((a, v) = > v === value ? a + 1 : a + 0.0);
    }
Copy the code

152. Addition Function (Precision loss problem)

 /** * @param { number } arg1 * @param { number } arg2 */
       export function add(arg1, arg2) {
       let r1, r2, m;
   try { r1 = arg1.toString().split(".") [1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".") [1].length } catch (e) { r2 = 0 }
    m = Math.pow(10.Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m
    }
Copy the code

153. Subtraction functions (Precision loss problem)

 /** * @param { number } arg1 * @param { number } arg2 */
       export function sub(arg1, arg2) {
       let r1, r2, m, n;
       try { r1 = arg1.toString().split(".") [1].length } catch (e) { r1 = 0 }
   try { r2 = arg2.toString().split(".") [1].length } catch (e) { r2 = 0 }
    m = Math.pow(10.Math.max(r1, r2));
    n = (r1 >= r2) ? r1 : r2;
    return Number(((arg1 * m - arg2 * m) / m).toFixed(n));
    }
Copy the code

154. Division function (Precision loss problem)

 /** * @param { number } num1 * @param { number } num2 */
       export function division(num1,num2){
       let t1,t2,r1,r2;
       try{
           t1 = num1.toString().split('. ') [1].length;
       }catch(e){
           t1 = 0;
       }
       try{
           t2=num2.toString().split(".") [1].length;
       }catch(e){
           t2=0;
   }
    r1=Number(num1.toString().replace(".".""));
    r2=Number(num2.toString().replace(".".""));
    return (r1/r2)*Math.pow(10,t2-t1);
    }
Copy the code

155. Multiplication Function (Precision loss problem)

 /** * @param { number } num1 * @param { number } num2 */
       export function mcl(num1,num2){
   let m=0,s1=num1.toString(),s2=num2.toString();
    try{m+=s1.split(".") [1].length}catch(e){}
    try{m+=s2.split(".") [1].length}catch(e){}
    return Number(s1.replace("."."")) *Number(s2.replace("."."")) /Math.pow(10,m);
    }
Copy the code

156. Recursive optimization (Tail recursion)

 /** * @param { function } f */
       export function tco(f) {
   let value;
       let active = false;
       let accumulated = [];
    
       return function accumulator() {
           accumulated.push(arguments);
           if(! active) { active =true;
               while (accumulated.length) {
                   value = f.apply(this, accumulated.shift());
               }
               active = false;
           returnvalue; }}; }Copy the code

157. Generate random integers

export function randomNumInteger(min, max) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * min + 1.10);
        case 2:
            return parseInt(Math.random() * (max - min + 1) + min, 10);
        default:
            return 0}}Copy the code

158. Remove whitespace

 /** * @param {string} STR String to be processed * @param {number} type Remove space type 1- All Spaces 2- Front and rear Spaces 3- Front and rear Spaces 4- Rear Spaces The default value is 1 */
       export function trim(str, type = 1) {
       if(type && type ! = =1&& type ! = =2&& type ! = =3&& type ! = =4) return;
       switch (type) {
           case 1:
               return str.replace(/\s/g."");
           case 2:
               return str.replace(/(^\s)|(\s*$)/g."");
           case 3:
               return str.replace(/(^\s)/g."");
           case 4:
           return str.replace(/(\s$)/g."");
        default:
            returnstr; }}Copy the code

159. Case conversion

/** * @param {string} STR String to be converted * @param {number} Type 1- All uppercase 2- All lowercase 3- Uppercase other - No conversion */

export function turnCase(str, type) {
    switch (type) {
        case 1:
            return str.toUpperCase();
        case 2:
            return str.toLowerCase();
        case 3:
            return str[0].toUpperCase() + str.substr(1).toLowerCase();
        default:
            returnstr; }}Copy the code

160. Random hexadecimal color hexColor

 /** ** /
       export function hexColor() {
    
       let str = The '#';
       let arr = [0.1.2.3.4.5.6.7.8.9.'A'.'B'.'C'.'D'.'E'.'F'];
       for (let i = 0; i < 6; i++) {
           let index = Number.parseInt((Math.random() * 16).toString());
       str += arr[index]
    }
    return str;
    }
Copy the code

161. Random hexadecimal color randomHexColorCode

 /** ** /
   export const randomHexColorCode = (a)= > {
    let n = (Math.random() * 0xfffff * 1000000).toString(16);
    return The '#' + n.slice(0.6);
    };
Copy the code

162. Escape HTML (against XSS attacks)

export const escapeHTML = str= >{
    str.replace(
        /[&<>'"]/g,
        tag =>
            ({
                '&': '& '.'<': '< '.'>': '> '."'": '& # 39; '.'"': '" '
            }[tag] || tag)
    );
};
Copy the code

163. Detect mobile /PC devices

export const detectDeviceType = (a)= > { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop'; };
Copy the code

164. Hide all specified tags

 / * * * example: hide (document. QuerySelectorAll (' img)) * /
    export const hideTag = (. el) = > [...el].forEach(e= > (e.style.display = 'none'));
Copy the code

165. Returns the effective style of the specified element

 /** * @param {element} el element node * @param {string} ruleName Specifies the element name */
    export const getStyle = (el, ruleName) = > getComputedStyle(el)[ruleName];
Copy the code

166. Check whether child elements are included

 /** * @param {element} parent * @param {element} child elementContains(document.querySelector('head'), document.querySelector('title')); // true */
    export const elementContains = (parent, child) = >parent ! == child && parent.contains(child);Copy the code

167. If the number exceeds the specified size plus the plus sign “+”, if the number exceeds 99, 99+ is displayed

 /** * @param {number} val Specifies the number to enter. * @param {number} maxNum Specifies the limit
       export const outOfNum = (val, maxNum) = >{
       val = val ? val0 :0;
       if (val > maxNum ) {
       return `${maxNum}+ `
    }else{
        returnval; }};Copy the code

168. How do I hide all specified elements

 const hide = (el) = > Array.from(el).forEach(e= > (e.style.display = 'none'));

 // Example: Hide all '' elements on the page?
 hide(document.querySelectorAll('img'))
Copy the code

169. How do I check if an element has a specified class?

Each node in the PAGE DOM has a classList object, which programmers can use to add, delete, and modify CSS classes on the node. With classList, programmers can also use it to determine whether a node is assigned a CSS class.

 const hasClass = (el, className) = > el.classList.contains(className)

 / / case
 hasClass(document.querySelector('p.special'), 'special') // true
Copy the code

170. How do I switch an element’s class?

 const toggleClass = (el, className) = > el.classList.toggle(className)

 // remove p special class with class 'special'
 toggleClass(document.querySelector('p.special'), 'special')
Copy the code

171. How do I get the scroll position of the current page?

 const getScrollPosition = (el = window) = > ({
   x: el.pageXOffset ! = =undefined ? el.pageXOffset : el.scrollLeft,
   y: el.pageYOffset ! = =undefined ? el.pageYOffset : el.scrollTop
 });

 / / case
 getScrollPosition(); // {x: 0, y: 200}
Copy the code

172. How do I scroll smoothly to the top of the page

 const scrollToTop = (a)= > {
   const c = document.documentElement.scrollTop || document.body.scrollTop;
   if (c > 0) {
     window.requestAnimationFrame(scrollToTop);
     window.scrollTo(0, c - c / 8); }}/ / case
 scrollToTop()
Copy the code
window.requestAnimationFrame() tells the browser that you want to execute an animation and asks the browser to call the specified callback to update the animation before the next redraw. This method takes as an argument a callback function that is executed before the browser's next redraw. RequestAnimationFrame: Advantage: It is up to the system to determine the timing of the callback function.60Hz refresh frequency, then each refresh interval will execute a callback function, will not cause frame loss, will not stall.window.requestAnimationFrame() tells the browser that you want to execute an animation and asks the browser to call the specified callback to update the animation before the next redraw. This method takes as an argument a callback function that is executed before the browser's next redraw. RequestAnimationFrame: Advantage: It is up to the system to determine the timing of the callback function.60Hz refresh frequency, then each refresh interval will execute a callback function, will not cause frame loss, will not stall.Copy the code

173. How do I check if a parent element contains child elements?

 const elementContains = (parent, child) = >parent ! == child && parent.contains(child);/ / case
 elementContains(document.querySelector('head'), document.querySelector('title')); 
 // true
 elementContains(document.querySelector('body'), document.querySelector('body')); 
 // false
Copy the code

174. How do I check if a specified element is visible in the viewport?

 const elementIsVisibleInViewport = (el, partiallyVisible = false) = > {
   const { top, left, bottom, right } = el.getBoundingClientRect();
   const { innerHeight, innerWidth } = window;
   return partiallyVisible
     ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
         ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
     : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
 };

 / / case
 elementIsVisibleInViewport(el); // Need left and right visibility
 elementIsVisibleInViewport(el, true); // Full screen (top, bottom, left, right
Copy the code

175. How do I get all the images in an element?

 const getImages = (el, includeDuplicates = false) = > {
   const images = [...el.getElementsByTagName('img')].map(img= > img.getAttribute('src'));
   return includeDuplicates ? images : [...new Set(images)];
 };

 // Example: includeDuplicates is true, indicating that duplicate elements need to be excluded
 getImages(document.true); // ['image1.jpg', 'image2.png', 'image1.png', '...']
 getImages(document.false); // ['image1.jpg', 'image2.png', '...']
Copy the code

176. How do I determine whether the device is a mobile device or a desktop/laptop?

 const detectDeviceType = (a)= >
   /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
     ? 'Mobile'
     : 'Desktop';

 / / case
 detectDeviceType(); // "Mobile" or "Desktop"
Copy the code

177.How to get the current URL?

 const currentURL = (a)= > window.location.href

 / / case
 currentURL() // 'https://google.com'
Copy the code

178. How do I create an object that contains the current URL parameters?

 const getURLParameters = url= >
   (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
     (a, v) = > ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
     {}
   );

 / / case
 getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
 getURLParameters('google.com'); / / {}
Copy the code

179. How do I turn a set of form elements into objects?

 const formToObject = form= >
   Array.from(new FormData(form)).reduce(
     (acc, [key, value]) = > ({
       ...acc,

[key]: value

​     }),
​     {}
   );

 / / case
 formToObject(document.querySelector('#form')); 
 // { email: '[email protected]', name: 'Test Name' }
Copy the code

180. How do I retrieve a set of properties indicated by a given selector from an object?

 const get = (from. selectors) = >
   [...selectors].map(s= >
     s
       .replace(/\[([^\[\]]*)\]/g.'. $1.)
       .split('. ')
       .filter(t= >t ! = =' ')
       .reduce((prev, cur) = > prev && prev[cur], from));const obj = { selector: { to: { val: 'val to select'}},target: [1.2, { a: 'test'}};// Example
 get(obj, 'selector.to.val'.'target[0]'.'target[2].a'); 
 // ['val to select', 1, 'test']
Copy the code

181. How to call a provided function after waiting a specified amount of time?

 const delay = (fn, wait, ... args) = >setTimeout(fn, wait, ... args); delay(function(text) {
     console.log(text);
   },
   1000.'later'
 ); 

 // Print 'later' after 1 second
Copy the code

182. How do I trigger a specific event on a given element and optionally pass custom data?

 const triggerEvent = (el, eventType, detail) = >
   el.dispatchEvent(new CustomEvent(eventType, { detail }));

 / / case
 triggerEvent(document.getElementById('myId'), 'click');
 triggerEvent(document.getElementById('myId'), 'click', { username: 'bob'}); CustomEvent functions include Event, CustomEvent, and dispatchEvent// Issue a resize built-in event to the window
 window.dispatchEvent(new Event('resize'))


 // Directly customize the Event using the Event constructor:
 var event = new Event('build');
 var elem = document.querySelector('#id')
 // Listen on events
 elem.addEventListener('build'.function (e) {... },false);
 // Trigger the event.elem.dispatchEvent(event); CustomEvent can create a more highly CustomEvent, along with some data, as follows:var myEvent = newCustomEvent(eventname, options); Where options can be: {detail: {... },bubbles: true.// Whether bubbles
   cancelable: false // Whether to cancel the default event} the detail can hold some initialization information, which can be called when triggered. Other attributes define whether the event has bubbling and so on. While built-in events are triggered by the browser based on certain actions, custom events need to be triggered manually. The dispatchEvent function is used to trigger an event: element.dispatchEvent(customEvent); The above code says that the customEvent event is triggered on element.// add an appropriate event listener
 obj.addEventListener("cat".function(e) { process(e.detail) });

 // create and dispatch the event
 var event = new CustomEvent("cat", {"detail": {"hazcheeseburger":true}}); obj.dispatchEvent(event); Using custom events requires compatibility issues, but jQuery is much simpler:// Bind custom events
 $(element).on('myCustomEvent'.function(){});

 // Trigger the event
 $(element).trigger('myCustomEvent');
 // In addition, you can also pass more parameter information when triggering custom events:

 $( "p" ).on( "myCustomEvent".function( event, myName ) {$(this ).text( myName + ", hi there!" );
 });
 $( "button" ).click(function () {$("p" ).trigger( "myCustomEvent"["John"]); });Copy the code

183. How do I remove event listeners from elements?

 const off = (el, evt, fn, opts = false) = > el.removeEventListener(evt, fn, opts);

 const fn = (a)= > console.log('! ');
 document.body.addEventListener('click', fn);
 off(document.body, 'click', fn); 
Copy the code

184. How do I get a readable format for a given number of milliseconds?

 const formatDuration = ms= > {
   if (ms < 0) ms = -ms;
   const time = {
     day: Math.floor(ms / 86400000),
     hour: Math.floor(ms / 3600000) % 24.minute: Math.floor(ms / 60000) % 60.second: Math.floor(ms / 1000) % 60.millisecond: Math.floor(ms) % 1000
   };
   return Object.entries(time)
     .filter(val= > val[1]! = =0)
     .map(([key, val]) = > `${val} ${key}${val ! = =1 ? 's' : ' '}`)
     .join(', ');
 };

 / / case
 formatDuration(1001); // '1 second, 1 millisecond'
 formatDuration(34325055574); 
 // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
Copy the code

185. How do I get the difference (in days) between two dates?

 const getDaysDiffBetweenDates = (dateInitial, dateFinal) = >
   (dateFinal - dateInitial) / (1000 * 3600 * 24);

 / / case
 getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); / / 9
Copy the code

186. How do I make GET requests to passed urls?

 const httpGet = (url, callback, err = console.error) = > {
   const request = new XMLHttpRequest();
   request.open('GET', url, true);
   request.onload = (a)= > callback(request.responseText);
   request.onerror = (a)= > err(request);
   request.send();
 };

 httpGet(
   'https://jsonplaceholder.typicode.com/posts/1'.console.log
 ); 

 // {"userId": 1, "id": 1, "title": "sample title", "body": "my text"}
Copy the code

187. How do I make a POST request on a passed URL?

 const httpPost = (url, data, callback, err = console.error) = > {
   const request = new XMLHttpRequest();
   request.open('POST', url, true);
   request.setRequestHeader('Content-type'.'application/json; charset=utf-8');
   request.onload = (a)= > callback(request.responseText);
   request.onerror = (a)= > err(request);
   request.send(data);
 };

 const newPost = {
   userId: 1.id: 1337.title: 'Foo'.body: 'bar bar bar'
 };
 const data = JSON.stringify(newPost);
 httpPost(
   'https://jsonplaceholder.typicode.com/posts',
   data,
   console.log
 ); 

 // {"userId": 1, "id": 1337, "title": "Foo", "body": "bar bar bar"}
Copy the code

188. How do I create a counter with a specified range, step, and duration for a specified selector?

 const counter = (selector, start, end, step = 1, duration = 2000) = > {
   let current = start,
     _step = (end - start) * step < 0 ? -step : step,
     timer = setInterval((a)= > {
       current += _step;
       document.querySelector(selector).innerHTML = current;
       if (current >= end) document.querySelector(selector).innerHTML = end;
       if (current >= end) clearInterval(timer);
     }, Math.abs(Math.floor(duration / (end - start))));
   return timer;
 };

 / / case
 counter('#my-id'.1.1000.5.2000); 
 // Create a 2-second timer for the element with 'id= "my-id"
Copy the code

189. How do I copy a string to the clipboard?

   const el = document.createElement('textarea');
   el.value = str;
   el.setAttribute('readonly'.' ');
   el.style.position = 'absolute';
   el.style.left = '-9999px';
   document.body.appendChild(el);
   const selected =
     document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
   el.select();
   document.execCommand('copy');
   document.body.removeChild(el);
   if (selected) {
     document.getSelection().removeAllRanges();
     document.getSelection().addRange(selected); }};/ / case
 copyToClipboard('Lorem ipsum'); 
 // 'Lorem ipsum' copied to clipboard
Copy the code

190. How do I determine whether a page’s browser TAB is focused?

 const isBrowserTabFocused = (a)= > !document.hidden;

 / / case
 isBrowserTabFocused(); // true
Copy the code

191. How do I create a directory (if no directory exists)?

 const fs = require('fs');
 const createDirIfNotExists = dir= >(! fs.existsSync(dir) ? fs.mkdirSync(dir) :undefined);

 / / case
 createDirIfNotExists('test'); Most of the above methods are very practical, can solve a lot of development process problems, we make good use of it.Copy the code

192. Date function encapsulation

function formatTime(date) {
  if(!!!!! date){if(! (dateinstanceof Date))
    date = new Date(date);
    var month = date.getMonth() + 1
    var day = date.getDate()
    return `${month}month${day}Day `; }}function formatDay(date) {
  if(!!!!! date){var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    return [year, month, day].map(formatNumber).join(The '-'); }}function formatDay2(date) {
  if(!!!!! date){var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    return [year, month, day].map(formatNumber).join('/'); }}function formatWeek(date){
  if(!!!!! date){var day = date.getDay();
    switch (day) {
      case 0:
        return 'Sunday'
        break;
      case 1:
        return 'Monday'
        break;
      case 2:
        return 'on Tuesday'
        break;
      case 3:
        return 'on Wednesday'
        break;
      case 4:
        return 'on Thursday
        break;
      case 5:
        return 'on Friday'
        break;
      case 6:
        return 'on Saturday
        break; }}}function formatHour(date){
  if(!!!!! date){var hour = new Date(date).getHours();
    var minute = new Date(date).getMinutes();
    return [hour, minute].map(formatNumber).join(':'); }}function timestamp(date, divisor=1000){
  if(date == undefined) {return;
  }else if(typeof date == 'number') {return Math.floor(date/divisor);
  }else if(typeof date == 'string') {var strs = date.split(/ [^ 0-9]);
    return Math.floor(+new Date(strs[0] | |0,(strs[1] | |0)- 1,strs[2] | |0,strs[3] | |0,strs[4] | |0,strs[5] | |0)/divisor);
  }else if(Date.prototype.isPrototypeOf(date)){
    return Math.floor(+date/divisor); }}function detimestamp(date){
  if(!!!!! date){return new Date(date*1000); }}function formatNumber(n) {// Add 0 to dates between 0 and 9
  n = n.toString()
  return n[1]? n :'0' + n
}

module.exports = {
  formatTime: formatTime,
  formatDay: formatDay,
  formatDay2: formatDay2,
  formatHour: formatHour,
  formatWeek: formatWeek,
  timestamp: timestamp,
  detimestamp: detimestamp
}
Copy the code

193. Timestamp to time

/** ** The timestamp is converted to year, month, day, minute, second */ number: the timestamp is passed in */ format: the returned format is supported, but the parameters must be the same as those in formateArr */  
function formatTime(number,format) {  
  
  var formateArr  = ['Y'.'M'.'D'.'h'.'m'.'s'];  
  var returnArr   = [];  
  
  var date = new Date(number * 1000);  
  returnArr.push(date.getFullYear());  
  returnArr.push(formatNumber(date.getMonth() + 1));  
  returnArr.push(formatNumber(date.getDate()));  
  
  returnArr.push(formatNumber(date.getHours()));  
  returnArr.push(formatNumber(date.getMinutes()));  
  returnArr.push(formatNumber(date.getSeconds()));  
  
  for (var i in returnArr)  
  {  
    format = format.replace(formateArr[i], returnArr[i]);  
  }  
  return format;  
} 

// Data conversion
function formatNumber(n) {  
  n = n.toString()  
  return n[1]? n :'0'+ n} examples of calls:var sjc = 1488481383;/ / timestamp
console.log(time.formatTime(sjc,'Y/M/D h:m:s'));// Convert to date: 2017/03/03 03:03:03
console.log(time.formatTime(sjc, 'h:m'));// Convert to date: 03:03
Copy the code

Get the context path in 194.js

Js to get the context path/ / js project root path, such as: http://localhost:8083/uimcardprj
    function getRootPath(){
        / / get the current url, such as: http://localhost:8083/uimcardprj/share/meun.jsp
        var curWwwPath=window.document.location.href;
        / / get the host address after directory, such as: uimcardprj/share/meun JSP
        var pathName=window.document.location.pathname;
        var pos=curWwwPath.indexOf(pathName);
        // Obtain the host address, for example, http://localhost:8083
        var localhostPaht=curWwwPath.substring(0,pos);
        // Get the project name with "/", for example, /uimcardprj
        var projectName=pathName.substring(0,pathName.substr(1).indexOf('/') +1);
        return(localhostPaht+projectName);
    }
Copy the code

195.JS size conversion B KB MB GB conversion method

function conver(limit){  
            var size = "";  
            if( limit < 0.1 * 1024) {// If less than 0.1KB, convert to B
                size = limit.toFixed(2) + "B";    
            }else if(limit < 0.1 * 1024 * 1024) {// If less than 0.1MB, convert to KB
                size = (limit / 1024).toFixed(2) + "KB";              
            }else if(limit < 0.1 * 1024 * 1024 * 1024) {// If less than 0.1GB, convert to MB
                size = (limit / (1024 * 1024)).toFixed(2) + "MB";  
            }else{ // Convert the rest to GB
                size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";  
            }  
              
            var sizestr = size + "";   
            var len = sizestr.indexOf("\.");  
            var dec = sizestr.substr(len + 1.2);  
            if(dec == "00") {// Remove the decimal part when the decimal point is 00
                return sizestr.substring(0,len) + sizestr.substr(len + 3.2);  
            }  
            return sizestr;  
}  
Copy the code

196. Js Full screen and exit full screen

function fullScreen() {
      var el = document.documentElement;
      var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;

​      //typeof rfs ! = "undefined" && rfsif (rfs) {
​        rfs.call(el);
​      } else if (typeof window.ActiveXObject ! = ="undefined") {
​        // For IE, this is actually a simulation of F11 pressing the keyboard to make the browser full screenvar wscript = new ActiveXObject("WScript.Shell");
​        if(wscript ! =null) {
​          wscript.SendKeys("{F11}"); }}}// Exit full screenfunction exitScreen() {
​      var el = document;
​      var cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen;

​      //typeof cfs ! = "undefined" && cfsif (cfs) {
​        cfs.call(el);
​      } else if (typeof window.ActiveXObject ! = ="undefined") {
​        // For IE, this is the same as fullScreen. Press F11 to exit fullScreenvar wscript = new ActiveXObject("WScript.Shell");
​        if(wscript ! =null) {
​          wscript.SendKeys("{F11}"); }}}Copy the code

Format the time to a few minutes ago, a few seconds ago

 /** * format time, convert to a few minutes ago, a few seconds ago * @param timestamp time, in milliseconds */
    function timeFormat(timestamp) {
        var mistiming = Math.round((Date.now() - timestamp) / 1000);
        var arrr = ['years'.'months'.'week'.'day'.'hour'.'minutes'.'秒'];
        var arrn = [31536000.2592000.604800.86400.3600.60.1];
        for (var i = 0; i < arrn.length; i++) {
            var inm = Math.floor(mistiming / arrn[i]);
            if(inm ! =0) {
                return inm + arrr[i] + 'before'; }}}Copy the code

198 Get the date n days before getDaysBeforeDate(10) 10 days before

GetDaysBeforeDate (10) before 10 days * @param day Number of days */
    function getDaysBeforeDate(day) {
        var date = new Date(),
            timestamp, newDate;
        timestamp = date.getTime();
        // Get the date three days ago
        newDate = new Date(timestamp - day * 24 * 3600 * 1000);
        var year = newDate.getFullYear();
        // Month +1 because months start with 0 in js
        var month = newDate.getMonth() + 1;
        var day = newDate.getDate();
        if (day < 10) { // If the day is less than 10, add 0 before it
            day = '0' + day;
        }
        if (month < 10) { // If the month is less than 10, add 0 before it
            month = '0' + month;
        }
        return [year, month, day].join('/');
    }
Copy the code

199. Obtain the forward classId in hash mode

 /** * get the jump classId, hash * @return return */

    $scope.getQueryString = function() {
        var url= {},
            a = ' ';
        (a = window.location.search.substr(1)) || (a = window.location.hash.split('? ') [1])
        a.split(/&/g).forEach(function(item) {
            url[(item = item.split('='))0]] = item[1];
        })
        return url
    }
Copy the code

200. Filter specifies fields

function filterArrBySex(data, name) {
        if(! name) {console.log(name)
            return data;
        } else {
            return data.filter(function(ele, index, self) {
                if (ele.name.includes(name)) {
                    return ele
                }
            })
        }
    }
Copy the code

201. Date of birth is obtained from identity card

 /** * Obtain date of birth according to id * @param idCard */
    function getBirthdayFromIdCard(idCard) {
        var birthday = "";
        if(idCard ! =null&& idCard ! ="") {
            if (idCard.length == 15) {
                birthday = "19" + idCard.substr(6.6);
            } else if (idCard.length == 18) {
                birthday = idCard.substr(6.8);
            }

            birthday = birthday.replace(/ (. {4})/(. {2})."$1 - $2 -");
        }

        return birthday;
    }
Copy the code

202. Obtaining age according to id card

/** * Get age according to id * @param UUserCard */
    function IdCard(UUserCard) {
        // Get the age
        var myDate = new Date(a);var month = myDate.getMonth() + 1;
        var day = myDate.getDate();
        var age = myDate.getFullYear() - UUserCard.substring(6.10) - 1;
        if (UUserCard.substring(10.12) < month || UUserCard.substring(10.12) == month && UUserCard.substring(12.14) <= day) {
            age++;
        }
        return age
    }
Copy the code
// Vue cart amount settlement
window.onload = function() {
    var vm = new Vue({
        el: '#app'.data: {
            items: [{
                    id: 1.name: The word "apple".price: 10.count: 1.url: "http://www.jq22.com/img/cs/500x500-1.png"
                },
                {
                    id: 2.name: "Butterfly".price: 8.count: 5.url: "http://www.jq22.com/img/cs/500x500-2.png"
                },
                {
                    id: 3.name: "The dog".price: 100.count: 1.url: "http://www.jq22.com/img/cs/500x500-3.png"
                },
                {
                    id: 4.name: "Flowers".price: 10.count: 1.url: "http://www.jq22.com/img/cs/500x500-4.png"}].search: ""
        },
        methods: {},filters: { / / filter
            numFilter: function(data, n) { //data==item.price Current filtered data n==2
                return "RMB" + data.toFixed(n)
            }
        },
        computed: { // Calculate attributes
            totalCount: function() {
                var n = 0;
                this.items.forEach((v, i) = > {
                    n += v.count
                });
                return n;
            },
            totalPrice: function() {
                var money = 0;
                this.items.forEach((v, i) = > {
                    money += v.count * v.price
                });
                return money;
            },
            searchFor: function() {
                if (!this.search) {
                    return this.items
                }
                return this.items.filter((v, i) = > {
                    if (v.name.indexOf(this.search) ! = =- 1) { // The match is successful
                        return v
                    }
                })
            }

        }
    })
}

// Set the iframe height
function setIframeHeight(sonH) { //debugger;            
    var height = 0;
    // Compare parent page heights, whichever is higher
    var parentH = $(window).height(); // The minimum iframe height should be the height of the browser viewport, otherwise the portal management page popup size will be limited
    height = parentH > sonH ? parentH : sonH;
    $('#mainIframe').height(height);

    // The child page has passed a value, covering the minimum height of iframe -2000px
    $("#mainIframe").css("min-height".'auto');
    $(".body-bg").css("height", height + 200);
    try {
        var childBody = $("#mainIframe") [0].contentWindow.document.getElementsByTagName("body") [0];
        //childBody.style.minHeight = height + "px";
    } catch (error) {
        if (error.message.indexOf("Blocked from frame") > - 1) console.warn("Current page exists across domains!"); }} (function($) {$("#username").keyup(function(event) {
        if (event.keyCode == 13The $()"#password").focus().select();
    });
    $("#password").keyup(function(event) {
        if (event.keyCode == 13The $()"#login-button").click();
    });
})(jQuery);


// Return to the top
function goTop() {
    window.scrollTo({
        top: 0.behavior: 'smooth'}); }window.onscroll = function() {
    var t = document.documentElement.scrollTop;
    if (t > 50) {$(".toTop").fadeIn();
    } else{$(".toTop").fadeOut(); }}function urlAnalysis() {
    var url = window.location.href;
    var paraString = url.substring(url.indexOf("?") + 1, url.length);
    var indexFirst = paraString.indexOf("&");
    var paraStringTitle = paraString.slice(0, indexFirst);
    paraStringElse = paraString.slice(indexFirst + 1, paraString.length);
    var paraStringUrl = paraStringElse;

    // Distinguish whether to pass parameters: functionId
    if (paraString.indexOf("functionId") > - 1) {
        var indexSecond = paraStringElse.indexOf("&");
        var paraStringFId = paraStringElse.slice(0, indexSecond);

        var functionId = paraStringFId.split("=") [1];
        var $body = angular.element(document.body);
        var $rootScope = $body.scope().$root;
        $rootScope.navFunctionId = functionId;

        paraStringUrl = paraStringElse.slice(indexSecond + 1, paraStringElse.length);
    }

    var title = paraStringTitle.split("=") [1= = ="undefined" ? "" : decodeURI(paraStringTitle.split("=") [1]);
    var indexUrl = paraStringUrl.indexOf("=");
    var iframeUrl = paraStringUrl.slice(indexUrl + 1, paraStringUrl.length);

    document.title = title;
    $("#mainIframe").attr("src", iframeUrl);
}



// Listen for the event enter to jump to the page
$scope.enterEvent = function(e) {
    var keycode = window.event ? e.keyCode : e.which;
    if (keycode == 13) {
        console.log($scope.searchVal)
        console.log('Listening successful')
        var baseUrl = '#/pages/knowlege/knowlegeSeach.html'
        window.open(baseUrl)
    }
};


function showDate() {
    var myDate = new Date(a);var year = myDate.getFullYear();
    var month = myDate.getMonth() + 1;
    month = month < 10 ? '0' + month : month;
    var date = myDate.getDate();
    date = date < 10 ? '0' + date : date;
    var weekDay = myDate.getDay();

    switch (weekDay) {
        case 0:
            weekDay = "Day";
            break;
        case 1:
            weekDay = "一";
            break;
        case 2:
            weekDay = "二";
            break;
        case 3:
            weekDay = "Three";
            break;
        case 4:
            weekDay = "Four";
            break;
        case 5:
            weekDay = "Five";
            break;
        case 6:
            weekDay = "Six";
            break;
            "name"
    }

    $scope.year = year;
    $scope.month = month;
    $scope.date = date;
    $scope.weekDay = weekDay;
}


// Get the jump classId, using hash
$scope.getQueryString = function() {
    var obg = {},
        a = ' ';
    (a = window.location.search.substr(1)) || (a = window.location.hash.split('? ') [1])
    a.split(/&/g).forEach(function(item) {
        obg[(item = item.split('='))0]] = item[1];
    })
    return obg
}
var classId = $scope.getQueryString();
Copy the code

203. Native JS slider validation

//event.clientX: the distance from the point below the mouse pointer to the left X-axis
window.onload = function() {
    Onmousedown onmousemove onMouseup
    var box = document.querySelector(".box")
    var btn = document.querySelector(".btn")
    var bg = document.querySelector(".bg")
    var text1 = document.querySelector(".text")
    // Encapsulating selector declarative functions can be promoted
    // function fun(){
    //				
    / /}
    var flag = false; / / tag
    btn.onmousedown = function(event) {
        var downx = event.clientX; // Get the distance from the X-axis after pressing
        btn.onmousemove = function(e) {
            var movex = e.clientX - downx; // How far does the slider slide
            // Range of movement
            if (movex > 0) {
                this.style.left = movex + "px";
                bg.style.width = movex + "px";
                if (movex >= box.offsetWidth - 40) {
                    // Verification succeeded
                    flag = true
                    text1.innerHTML = "Verification successful"
                    text1.style.color = "#fff"
                    // Clear the event
                    btn.onmousedown = null;
                    btn.onmousemove = null; }}}}// Release event
    btn.onmouseup = function() {
        // Clear the event
        btn.onmousemove = null;
        if (flag) return;
        this.style.left = 0;
        bg.style.width = 0 + "px"; }}Copy the code

204. Pure JS Infinite loading waterfall (original)

// Integer encapsulation between random [m,n]
function randomNumber(m, n) {
    return Math.floor(Math.random() * (n - m + 1) + m);
}
// Random color encapsulation
function randomColor() {
    return "rgb(" + randomNumber(0.255) + "," + randomNumber(0.255) + "," + randomNumber(0.255) + ")";
}

// Get the current scrollTop
var scrollTopDistance;
// Get all ul's
var uls = document.querySelectorAll("ul");
var i = 0;
var k = i;

function waterFall() {
    for (i = k; i < k + 4; i++) {
        / / create the li
        var li = document.createElement("li");
        // Random color
        li.style.backgroundColor = randomColor();
        // Random height
        li.style.height = randomNumber(120.400) + "px";
        // Manually convert to a string
        li.innerHTML = i + 1 + "";
        // Insert into the corresponding ul
        // Determine which ul has the lower height, and insert the li created this time into the ul
        var index = 0; // Record the subscript
        for (var j = 0; j < uls.length; j++) {
            if(uls[j].offsetHeight < uls[index].offsetHeight) { index = j; }}// Insert element nodes into the document
        uls[index].appendChild(li);
    }
    k = i;
    return uls[index].offsetHeight;
}
waterFall();
// The onmouseWheel event is used because there is no mousewheel on the right
window.onmousewheel = function() {
    // Get the height of the window, compatible with the browser
    var windowH = document.documentElement.clientHeight;
    // The distance between the wheel and top, compatible with the browser
    var scrollH = document.documentElement.scrollTop ||
        document.body.scrollTop;
    // Get the visible height of the window
    var documentH = document.documentElement.scrollHeight ||
        document.body.scrollHeight;
    // Window height + distance between the wheel and the top > window visible height -200
    if (windowH + scrollH > documentH - 200) {
        // Execute this function
        waterFall()
    }
}
Copy the code

205. Compare the height of two elements in jQuery

$(*function* () {*var* w_max = 0;
  *// Get the maximum height *
  $("#MenuNavigation li").each(*function* () {*var* w = $(*this*).innerWidth(); w_max = w > w_max ? w : w_max; $(})"#MenuNavigation li").width(w_max)
  *// Assign the maximum height to all elements, *
})
Copy the code

206.js Periodically clear cache, store cache, and obtain cache

// Encapsulate local storage methods
export const storage = {
  set: function(variable, value, ttl_ms) {
    var data = { value: value, expires_at: new Date(ttl_ms).getTime() };
    localStorage.setItem(variable.toString(), JSON.stringify(data));
  },
  get: function(variable) {
    var data = JSON.parse(localStorage.getItem(variable.toString()));
    if(data ! = =null) {
      debugger
      if(data.expires_at ! = =null && data.expires_at < new Date().getTime()) {
        localStorage.removeItem(variable.toString());
      } else {
        returndata.value; }}return null; }, remove(key) { localStorage.removeItem(key); }}Copy the code

207. Array dimension reduction

// Array dimension reduction
reduceDimension(arr) {
      var reduced = [];
      for (var i = 0; i < arr.length; i++) {
        reduced = reduced.concat(arr[i]);
      }
      return reduced;
}
Copy the code

208. Set cookies, obtain cookies, and delete cookies

 var cookieUtil = {
  getCookie: function (name) {
    var arrCookie = document.cookie.split("; ");
    for (var i = 0; i < arrCookie.length; i++) {
      var cookieItem = arrCookie[i].split('=');
      if (cookieItem[0] == name) {
        return cookieItem[1]; }}return undefined;
  },
  setCookie: function (name, value, expires, path, domain, secure) {
    var cookieText = encodeURIComponent(name) + "=" +
      encodeURIComponent(value);
    if (expires instanceof Date) {
      cookieText += "; expires=" + expires.toGMTString();
    }
    if (path) {
      cookieText += "; path=" + path;
    }
    if (domain) {
      cookieText += "; domain=" + domain;
    }
    if (secure) {
      cookieText += "; secure";
    }
    document.cookie = cookieText;
  },
  removeCookie: function (name, path, domain, secure) {
    this.set(name, "".new Date(0), path, domain, secure); }}Copy the code

209. Determine if it is an outer chain

/** * @description checks whether it is an external chain * @param path * @returns {Boolean} */
   export function isExternal(path) {
     return /^(https? :|mailto:|tel:)/.test(path);
   }

Copy the code

210. Verify whether the password is less than 6 characters

/** * @description Specifies whether the verification password contains less than six characters. * @param STR * @returns {Boolean} */
      export function isPassword(str) {
        return str.length >= 6;
      }
      
Copy the code

211. Check whether it is a number

/** * @description Checks whether it is a number * @param value * @returns {Boolean} */
   export function isNumber(value) {
     const reg = / ^ [0-9] * $/;
     return reg.test(value);
   }
Copy the code

212. Check if it is a name

 /** * @description Check whether it is a name * @param value * @returns {Boolean} */
    export function isName(value) {
      const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/;
      return reg.test(value);
    }
Copy the code

213. Check whether it is an IP address

/** * @description Checks whether it is IP * @param IP * @returns {Boolean} */
   export function isIP(ip) {
     const reg = / ^ (\ d {1, 2} | 1 | 2 \ d \ d \ d [0-4] 25 [0-5]) | \. (\ d {1, 2} \ d \ d | 2 | 1 [0-4] \ | d 25 [0-5]) \. (\ d {1, 2} \ d \ d | 2 | 1 [0-4] \ | d 25 [0-5]) \. (\ d {1, 2} \ d \ d | 2 | 1 [0-4]\d|25[0-5])$/;
     return reg.test(ip);
   }
Copy the code

214. Determine if it’s a traditional site

/** * @description Checks whether it is a traditional website * @param URL * @returns {Boolean} */
   export function isUrl(url) {
     const reg = /^(https? |ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?) (\. (25 [0 to 5] | 2 [0 to 4] [0-9] [0-9] {2} | 1 | [1-9]? [0-9])){3}|([a-zA-Z0-9-]+\.) *[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA- Z0-9.,?'\\+&%$#=~_-]+))*$/;
     return reg.test(url);
   }
Copy the code

215. Check lowercase letters

/** * @description Checks whether it is a lowercase letter * @param STR * @returns {Boolean} */
   export function isLowerCase(str) {
     const reg = /^[a-z]+$/;
     return reg.test(str);
   }
Copy the code

216. Check for capital letters

/** * @description Checks whether it is an uppercase letter * @param STR * @returns {Boolean} */
   export function isUpperCase(str) {
     const reg = /^[A-Z]+$/;
     return reg.test(str);
   }
Copy the code

217. Check if it begins with a capital letter

/** * @description Checks whether it starts with an uppercase letter * @param STR * @returns {Boolean} */
   export function isAlphabets(str) {
     const reg = /^[A-Za-z]+$/;
     return reg.test(str);
   }
Copy the code

218. Check if it is a string

/** * @description Checks whether it is a string * @param STR * @returns {Boolean} */
   export function isString(str) {
     return typeof str === "string" || str instanceof String;
   }
Copy the code

219. Check if it is an array

/ * * * * @ @ the description to judge whether the array param arg * @ returns {arg is any [] | Boolean} * /
  export function isArray(arg) {
     if (typeof Array.isArray === "undefined") {
   return Object.prototype.toString.call(arg) === "[object Array]";
     }
     return Array.isArray(arg);
   }
Copy the code

Check whether it is a port number

/** * @description Checks whether the port number is * @param STR * @returns {Boolean} */
   export function isPort(str) {
     const reg = /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
     return reg.test(str);
   }
Copy the code

221. Check if it is a cell phone number

/** * @description Checks whether it is a mobile phone number * @param STR * @returns {Boolean} */
   export function isPhone(str) {
     const reg = /^1\d{10}$/;
     return reg.test(str);
   }
Copy the code

222. Check whether it is id number (second generation)

/** * @description Checks whether it is the id number (the second generation) * @param STR * @returns {Boolean} */
   export function isIdCard(str) {
     const reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
     return reg.test(str);
   }
Copy the code

223. Determine if it is a mailbox

/** * @description Checks whether it is a mailbox * @param STR * @returns {Boolean} */
   export function isEmail(str) {
     const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
     return reg.test(str);
   }
Copy the code

224. Check whether it is Chinese

/** * @description Checks whether Chinese * @param STR * @returns {Boolean} */
   export function isChina(str) {
     const reg = / ^ [\ u4E00 - \ u9FA5] {2, 4} $/;
     return reg.test(str);
   }
Copy the code

225. Check whether it is empty

/** * @description Checks whether it is empty * @param STR * @returns {Boolean} */
      export function isBlank(str) {
        return (
    str == null ||
  false ||
   str === "" ||
   str.trim() === "" ||
   str.toLocaleLowerCase().trim() === "null"
     );
   }
Copy the code

226. Check whether it is a fixed line

/** * @description Checks whether it is a fixed phone * @param STR * @returns {Boolean} */
   export function isTel(str) {
     const reg = / ^ (400 | 800) ([0-9 \ \ -] {7, 10}) | (([0-9] {4} | [0-9] {3}) (-) |?) ? ([0-9] {7, 8}) ((- | | turn) * ([0-9] {1, 4}))? $/;
     return reg.test(str);
   }
Copy the code

227. Check if it is a digit with at most two decimal digits

/** * @description Checks whether the string is a number with a maximum of two decimal digits * @param STR * @returns {Boolean} */
   export function isNum(str) {
     const reg = / ^ \ d + (\ \ d {1, 2})? $/;
     return reg.test(str);
   }
Copy the code

228. Determine the longitude from -180.0 to +180.0 (integer part is 0 to 180, must enter 1 to 5 decimal places)

/** * @description Determine the longitude from -180.0 to +180.0 (integers ranging from 0 to 180, 1 to 5 decimal digits must be entered) * @param STR * @returns {Boolean} */
   export function isLongitude(str) {
     const reg = / ^ [- | +]? (0? . \ d {1, 2} \ \ d {1, 5} | 1 [0]? \ d {1} \ \ d {1, 5} | \. 180 $/ 0} {1 and 5);
     return reg.test(str);
   }
Copy the code

229. Determine latitude from -90.0 to +90.0 (integer part is 0 to 90, must enter 1 to 5 decimal places)

/** * @description Check the latitude from -90.0 to +90.0 (integers ranging from 0 to 90 must contain 1 to 5 decimal digits) * @param STR * @returns {Boolean} */
   export function isLatitude(str) {
     const reg = / ^ [- | +]? ([0 to 8]? \ d {1} \ \ d {1, 5} | \. 90 $/ 0} {1 and 5);
     return reg.test(str);
   }
Copy the code

230. RTSP verification as long as there is RTSP ://

/** * @description RTSP verification, as long as RTSP :// * @param STR * @returns {Boolean} */
  export function isRTSP(str) {
     const reg = / ^ RTSP: \ \ / ([a-z] {0, 10} :. {0, 10} @)? (\ d {1, 2} \ d \ d | 2 | 1 \ | d 25 [0-4] [0-5]) \. (\ d {1, 2} \ d \ d | 2 | 1 \ | d 25 [0-4] [0-5]) \. (\ d {1, 2} \ d \ d | 2 | 1 [0-4] \ | d 25 [0-5]) \. (\ d {1, 2} \ d \ d | 2 | 1 [0 -4]\d|25[0-5])$/;
     const reg1 = / ^ RTSP: \ \ / ([a-z] {0, 10} :. {0, 10} @)? (\ d {1, 2} \ d \ d | 2 | 1 \ | d 25 [0-4] [0-5]) \. (\ d {1, 2} \ d \ d | 2 | 1 \ | d 25 [0-4] [0-5]) \. (\ d {1, 2} \ d \ d | 2 | 1 [0-4] \ | d 25 [0-5]) \. (\ d {1, 2} \ d \ d | 2 | 1 [0 25 [4] \ d | 0 to 5] : [0-9] {1, 5} /;
     const reg2 = / ^ RTSP: \ \ / ([a-z] {0, 10} :. {0, 10} @)? (\ d {1, 2} \ d \ d | 2 | 1 \ | d 25 [0-4] [0-5]) \. (\ d {1, 2} \ d \ d | 2 | 1 \ | d 25 [0-4] [0-5]) \. (\ d {1, 2} \ d \ d | 2 | 1 [0-4] \ | d 25 [0-5]) \. (\ d {1, 2} \ d \ d | 2 | 1 [0 -4]\d|25[0-5])\//;
     return reg.test(str) || reg1.test(str) || reg2.test(str);
   }
Copy the code

231. Check the Internet Explorer version and check whether the browser is not Internet Explorer

function IEVersion() {
	var userAgent = navigator.userAgent; // Get the browser's userAgent string
	var isIE = userAgent.indexOf("compatible") > - 1 && userAgent.indexOf("MSIE") > - 1; // Check whether IE<11 browser
	var isEdge = userAgent.indexOf("Edge") > - 1 && !isIE; // Check whether the Edge browser is IE
	var isIE11 = userAgent.indexOf('Trident') > - 1 && userAgent.indexOf("The rv: 11.0") > - 1;
	if (isIE) {
		var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
		reIE.test(userAgent);
		var fIEVersion = parseFloat(RegExp["$1"]);
		if (fIEVersion == 7) {
			return 7;
		} else if (fIEVersion == 8) {
			return 8;
		} else if (fIEVersion == 9) {
			return 9;
		} else if (fIEVersion == 10) {
			return 10;
		} else {
			return 6; / / IE version < = 7}}else if (isEdge) {
		return 'edge'; //edge
	} else if (isIE11) {
		return 11; //IE11  
	} else {
		return - 1; // Not Internet Explorer}}Copy the code

232. Array deduplication

Solution a:Set + ...

function noRepeat(arr) {
  return [...new Set(arr)];
}
noRepeat([1.2.3.1.2.3])
Copy the code

Scheme 2:Set + Array.from

function noRepeat(arr) {
  return Array.from(new Set(arr));
}
noRepeat([1.2.3.1.2.3])
Copy the code

Scheme three: double traversal comparison subscripts

function noRepeat(arr) {
  return arr.filter((v, idx) = >idx == arr.lastIndexOf(v))
}
noRepeat([1.2.3.1.2.3])
Copy the code

Scheme 4: Single traversal + Object feature

The property of Object is that the Key does not duplicate. Values are used here because the type can be preserved and keys will become a string.

function noRepeat(arr) {
  return Object.values(arr.reduce((s,n) = >{
    s[n] = n;
    return s
  },{}))
}
noRepeat([1.2.3.1.2.3])
Copy the code

Afterword.

There are other variants of the above scheme.

233. Find array is the largest

Solution a:Math.max + ...

function arrayMax(arr) {
  return Math.max(... arr); } arrayMax([- 1.4 -.5.2.0])
Copy the code

Scheme 2:Math.max + apply

function arrayMax(arr) {
  return Math.max.apply(Math, arr)
}
arrayMax([- 1.4 -.5.2.0])
Copy the code

Solution 3:Math.max+ traversal

function arrayMax(arr) {
  return arr.reduce((s,n) = >Math.max(s, n))
}
arrayMax([- 1.4 -.5.2.0])
Copy the code

Scheme 4: comparison, conditional operation + ergodic

function arrayMax(arr) {
  return arr.reduce((s,n) = >s>n? s:n) } arrayMax([- 1.4 -.5.2.0])
Copy the code

Scheme 5: Sort

function arrayMax(arr) {
  return arr.sort((n,m) = >m-n)[0]
}
arrayMax([- 1.4 -.5.2.0])
Copy the code

234. Find the smallest array

Same as above, I don’t see why there are two questions.

  1. Math.maxSwitch toMath.min
  2. s>n? s:nFor ` s
  3. (n,m)=>m-nSwitch to(n,m)=>n-mOr you could just take the last element

235. Return an array split with size as length

Plan 1: Array.from + slice

function chunk(arr, size = 1) {
  return Array.from(
    {
      length: Math.ceil(arr.length / size),
    },
    (v, i) => arr.slice(i * size, i * size + size)
  );
}
chunk([1.2.3.4.5.6.7.8].3)
Copy the code

Scheme 2: array. from + splice

function chunk(arr, size = 1) {
  return Array.from(
    {
      length: Math.ceil(arr.length / size),
    },
    (v, i) => arr.splice(0, size)
  );
}
chunk([1.2.3.4.5.6.7.8].3)
Copy the code

Scheme 3: Traverse + splice

function chunk(arr, size = 1) {
    var _returnArr = [];
    while(arr.length){
        _returnArr.push(arr.splice(0, size))
    }
    return _returnArr
}
chunk([1.2.3.4.5.6.7.8].3)
Copy the code

Checks the number of occurrences of an element in an array

Solution 1: Reduce

function countOccurrences(arr, value) {
  return arr.reduce((a, v) = > (v === value ? a + 1 : a + 0), 0);
}
countOccurrences([1.2.3.4.5.1.2.1.2.3].1)
Copy the code

Scheme 2: Filter

function countOccurrences(arr, value) {
  return arr.filter(v= >v===value).length
}
countOccurrences([1.2.3.4.5.1.2.1.2.3].1)
Copy the code

236. Flat arrays

Plan 1: Recursion +…

function flatten(arr, depth = - 1) {
  if (depth === - 1) {
    return[].concat( ... arr.map((v) = > (Array.isArray(v) ? this.flatten(v) : v))
    );
  }
  if (depth === 1) {
    return arr.reduce((a, v) = > a.concat(v), []);
  }
  return arr.reduce(
    (a, v) = > a.concat(Array.isArray(v) ? this.flatten(v, depth - 1) : v),
    []
  );
}
flatten([1[2[3]]])
Copy the code

Scheme 2: ES6 native Flat

function flatten(arr, depth = Infinity) {
  return arr.flat(depth)
}
flatten([1[2[3]]])
Copy the code

Compare two arrays and return the different elements

Solution 1: Filter + includes

There is something wrong with his text, 4 and 5 of the following methods are not returned

function diffrence(arrA, arrB) {
  return arrA.filter((v) = >! arrB.includes(v)); } diffrence([1.2.3], [3.4.5.2])
Copy the code

We need to do it again

function diffrence(arrA, arrB) {
  return arrA.filter((v) = >! arrB.includes(v)) .concat(arrB.filter((v) = >! arrA.includes(v))); } diffrence([1.2.3], [3.4.5.2])
Copy the code

Scheme 2: Hash + traversal

This is a variant of plan 1, which optimizes the performance of Includes.

237. Return the same element in both arrays

Solution 1: Filter + includes

function intersection(arr1, arr2) {
  return arr2.filter((v) = > arr1.includes(v));
}
intersection([1.2.3], [3.4.5.2])
Copy the code

Scheme 2: Use hash for the same variation

function intersection(arr1, arr2) {
    var set = new Set(arr2)
  return arr1.filter((v) = > set.has(v));
}
intersection([1.2.3], [3.4.5.2])
Copy the code

238. Delete N elements from the right

Plan 1: Slice

function dropRight(arr, n = 0) {
  return n < arr.length ? arr.slice(0, arr.length - n) : [];
}
dropRight([1.2.3.4.5].2)
Copy the code

Plan 2: Splice

function dropRight(arr, n = 0) {
  return arr.splice(0, arr.length - n)
}
dropRight([1.2.3.4.5].2)
Copy the code

Plan 3: Slice another

function dropRight(arr, n = 0) {
  return arr.slice(0, -n)
}
dropRight([1.2.3.4.5].2)
Copy the code

Solution 4: Change the length

function dropRight(arr, n = 0) {
    arr.length = Math.max(arr.length - n, 0)
    return arr
}
dropRight([1.2.3.4.5].2)
Copy the code

239. Intercepts the first qualifying element and subsequent elements

Plan 1: Slice + loop

function dropElements(arr, fn) {
  while(arr.length && ! fn(arr[0])) arr = arr.slice(1);
  return arr;
}
dropElements([1.2.3.4.5.1.2.3], (v) => v == 2)
Copy the code

Scheme 2: findIndex + Slice

function dropElements(arr, fn) {
  return arr.slice(Math.max(arr.findIndex(fn), 0));
}
dropElements([1.2.3.4.5.1.2.3], (v) => v === 3)
Copy the code

Option 3: Splice + loop

function dropElements(arr, fn) {
  while(arr.length && ! fn(arr[0])) arr.splice(0.1);
  return arr;
}
dropElements([1.2.3.4.5.1.2.3], (v) => v == 2)
Copy the code

240. Return the element in the array with the subscript interval NTH

Solution 1: Filter

function everyNth(arr, nth) {
  return arr.filter((v, i) = > i % nth === nth - 1);
}
everyNth([1.2.3.4.5.6.7.8].2)
Copy the code

Plan 2: Plan 1 modify the judgment conditions

function everyNth(arr, nth) {
  return arr.filter((v, i) = > (i+1) % nth === 0);
}
everyNth([1.2.3.4.5.6.7.8].2)
Copy the code

241. Return the NTH element of the array (negative numbers supported)

Plan 1: Slice

function nthElement(arr, n = 0) {
  return (n >= 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
}
nthElement([1.2.3.4.5].0)
nthElement([1.2.3.4.5].- 1)
Copy the code

Scheme two: the ternary operator

function nthElement(arr, n = 0) {
  return (n >= 0 ? arr[0] : arr[arr.length + n])
}
nthElement([1.2.3.4.5].0)
nthElement([1.2.3.4.5].- 1)
Copy the code

242. Return the array header element

Solution a:

function head(arr) {
  return arr[0];
}
head([1.2.3.4])
Copy the code

Scheme 2:

function head(arr) {
  return arr.slice(0.1) [0];
}
head([1.2.3.4])
Copy the code

243. Return the last element of the array

Solution a:

function last(arr) {
  return arr[arr.length - 1];
}
Copy the code

Scheme 2:

function last(arr) {
  return arr.slice(- 1) [0];
}
last([1.2.3.4.5])
Copy the code

245. Array scrambling

Scheme 1: shuffle algorithm

function shuffle(arr) {
  let array = arr;
  let index = array.length;

  while (index) {
    index -= 1;
    let randomInedx = Math.floor(Math.random() * index);
    let middleware = array[index];
    array[index] = array[randomInedx];
    array[randomInedx] = middleware;
  }

  return array;
}
shuffle([1.2.3.4.5])
Copy the code

Scheme 2: Sort + random

function shuffle(arr) {
  return arr.sort((n,m) = >Math.random() - . 5)
}
shuffle([1.2.3.4.5])
Copy the code

246. Convert pseudoarrays to arrays

Plan 1: array. from

Array.from({length: 2})
Copy the code

Prototype: Slice

Array.prototype.slice.call({length: 2.1:1})
Copy the code

Prototype

Array.prototype.splice.call({length: 2.1:1},0)
Copy the code

Browser object BOM

195. Check whether the browser supports CSS properties

@param {String} key - The CSS property is the name of the property and does not need to be prefixed. * @returns {String} - The supported property */
function validateCssKey(key) {
  const jsKey = toCamelCase(key); // Some CSS properties are formed with a hyphen
  if (jsKey in document.documentElement.style) {
    return key;
  }
  let validKey = "";
  // The property name is the prefix form in JS, and the property value is the prefix form in CSS
  // On trial, Webkit is also lowercase Webkit
  const prefixMap = {
    Webkit: "-webkit-".Moz: "-moz-".ms: "-ms-".O: "-o-"};for (const jsPrefix in prefixMap) {
    const styleKey = toCamelCase(`${jsPrefix}-${jsKey}`);
    if (styleKey in document.documentElement.style) {
      validKey = prefixMap[jsPrefix] + key;
      break; }}return validKey;
}

/** * converts a hyphenated string to a hump named string */
function toCamelCase(value) {
  return value.replace(/-(\w)/g, (matched, letter) => {
    return letter.toUpperCase();
  });
}

/** * Check whether the browser supports a CSS property value (ES6) * @param {String} key - The name of the CSS property value to be checked * @param {String} value - The CSS property value to be checked (without prefix) * @returns {String} - Returns the browser-supported attribute value */
function valiateCssValue(key, value) {
  const prefix = ["-o-"."-ms-"."-moz-"."-webkit-".""];
  const prefixValue = prefix.map((item) = > {
    return item + value;
  });
  const element = document.createElement("div");
  const eleStyle = element.style;
  // Apply each prefix case, and finally apply no prefix case, to see how the browser works in the end
  // The last element in prefix should be ''.
  prefixValue.forEach((item) = > {
    eleStyle[key] = item;
  });
  return eleStyle[key];
}

/** * Check whether the browser supports a CSS property value * @param {String} key - The CSS property name of the checked property value * @param {String} value - THE CSS property value to be checked (without prefix) * @returns {String} - Returns the browser-supported property value */
function valiateCssValue(key, value) {
  var prefix = ["-o-"."-ms-"."-moz-"."-webkit-".""];
  var prefixValue = [];
  for (var i = 0; i < prefix.length; i++) {
    prefixValue.push(prefix[i] + value);
  }
  var element = document.createElement("div");
  var eleStyle = element.style;
  for (var j = 0; j < prefixValue.length; j++) {
    eleStyle[key] = prefixValue[j];
  }
  return eleStyle[key];
}

function validCss(key, value) {
  const validCss = validateCssKey(key);
  if (validCss) {
    return validCss;
  }
  return valiateCssValue(key, value);
}
Copy the code

segmentfault.com/a/11… It has forEach in it.

247. Returns the current web page address

Solution 1: Location

function currentURL() {
  return window.location.href;
}
currentURL()
Copy the code

Plan 2: A label

function currentURL() {
  var el = document.createElement('a')
  el.href = ' '
  return el.href
}
currentURL()
Copy the code

Gets the scroll bar position

function getScrollPosition(el = window) {
  return {
    x: el.pageXOffset ! = =undefined ? el.pageXOffset : el.scrollLeft,
    y: el.pageYOffset ! = =undefined ? el.pageYOffset : el.scrollTop,
  };
}
Copy the code

Get parameters from the URL

Solution 1: Regular + Reduce

function getURLParameters(url) {
  return url
    .match(/([^?=&]+)(=([^&]*))/g)
    .reduce(
      (a, v) = > (
        (a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a
      ),
      {}
    );
}
getURLParameters(location.href)
Copy the code

Scheme 2: Split + Reduce

function getURLParameters(url) {
  return url
    .split('? ') / / take? segmentation
    .slice(1) // Skip the first part
    .join() / / stitching
    .split('&')/ / & division
    .map(v= >v.split('=')) / / = segmentation
    .reduce((s,n) = >{s[n[0]] = n[1];return s},{})
}
getURLParameters(location.href)
// getURLParameters('')
Copy the code

Scheme 3: URLSearchParams

249. Page jump, whether record in history

Solution a:

function redirect(url, asLink = true) {
  asLink ? (window.location.href = url) : window.location.replace(url);
}
Copy the code

Scheme 2:

function redirect(url, asLink = true) {
  asLink ? window.location.assign(url) : window.location.replace(url);
}
Copy the code

Scroll bar back to top animation

Option 1: C-C / 8

C is undefined

function scrollToTop() {
  const scrollTop =
    document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  } else {
    window.cancelAnimationFrame(scrollToTop);
  }
}
scrollToTop()
Copy the code

After the modification

function scrollToTop() {
  const scrollTop =
    document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, scrollTop - scrollTop / 8);
  } else {
    window.cancelAnimationFrame(scrollToTop);
  }
}
scrollToTop()
Copy the code

251. Copy text

Solution a:

function copy(str) {
  const el = document.createElement("textarea");
  el.value = str;
  el.setAttribute("readonly"."");
  el.style.position = "absolute";
  el.style.left = "-9999px";
  el.style.top = "-9999px";
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0
      ? document.getSelection().getRangeAt(0)
      : false;
  el.select();
  document.execCommand("copy");
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected); }}Copy the code

Solution 2: cliboard.js

252. Check the device type

Plan 1: UA

function detectDeviceType() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )
    ? "Mobile"
    : "Desktop";
}
detectDeviceType()
Copy the code

Scheme 2: Event attributes

function detectDeviceType() {
  return ("ontouchstart" in window || navigator.msMaxTouchPoints)
    ? "Mobile"
    : "Desktop";
}
detectDeviceType()
Copy the code

253.Cookie

increase

function setCookie(key, value, expiredays) {
  var exdate = new Date(a); exdate.setDate(exdate.getDate() + expiredays);document.cookie =
    key +
    "=" +
    escape(value) +
    (expiredays == null ? "" : "; expires=" + exdate.toGMTString());
}
Copy the code

delete

function delCookie(name) {
  var exp = new Date(a); exp.setTime(exp.getTime() -1);
  var cval = getCookie(name);
  if(cval ! =null) {
    document.cookie = name + "=" + cval + "; expires="+ exp.toGMTString(); }}Copy the code

check

function getCookie(name) {
  var arr,
    reg = new RegExp("(^| )" + name + "= (/ ^; (*). | $)");
  if ((arr = document.cookie.match(reg))) {
    return arr[2];
  } else {
    return null; }}Copy the code

empty

Sometimes we want to clear, but we can’t get all the cookies. At this point we can use fill, and then empty.

The Date of the Date

254. Timestamp is converted to time

  • The default value is the current time conversion result
  • IsMs is whether the timestamp is millisecond
function timestampToTime(timestamp = Date.parse(new Date()), isMs = true) {
  const date = new Date(timestamp * (isMs ? 1 : 1000));
  return `${date.getFullYear()}-${
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
  }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}
Copy the code
  1. The complement can be changed to padStart
  2. The complement can also be changed to slice

If I am overseas, I will have some problems. I usually use moment to solve them. If you want to see the original

Gets the current timestamp

Based on the last question that came to mind

Date.parse(new Date())

Date.now()

+new Date()

Document object DOM

255 Fixed scroll bar

/** * Function description: some business scenarios, such as pop-up box, need to prohibit page scrolling, this is compatible with Android and iOS prohibit page scrolling solution */

let scrollTop = 0;

function preventScroll() {
  // Store the current scroll position
  scrollTop = window.scrollY;

  // Set the scrollable area to a fixed position. The scrollable area cannot be scrolled when its height is 0
  document.body.style["overflow-y"] = "hidden";
  document.body.style.position = "fixed";
  document.body.style.width = "100%";
  document.body.style.top = -scrollTop + "px";
  // document.body.style['overscroll-behavior'] = 'none'
}

function recoverScroll() {
  document.body.style["overflow-y"] = "auto";
  document.body.style.position = "static";
  // document.querySelector('body').style['overscroll-behavior'] = 'none'

  window.scrollTo(0, scrollTop);
}
Copy the code

256 Check whether the current location is at the bottom of the page

  • The return value is true/false
function bottomVisible() {
  return (
    document.documentElement.clientHeight + window.scrollY >=
    (document.documentElement.scrollHeight ||
      document.documentElement.clientHeight)
  );
}
Copy the code

257 Determine whether the element is visible

  • PartiallyVisible: Indicates whether it is fully visible
function elementIsVisibleInViewport(el, partiallyVisible = false) {
  const { top, left, bottom, right } = el.getBoundingClientRect();

  return partiallyVisible
    ? ((top > 0 && top < innerHeight) ||
        (bottom > 0 && bottom < innerHeight)) &&
        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
    : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}
Copy the code

258. Get element CSS styles

function getStyle(el, ruleName) {
  return getComputedStyle(el, null).getPropertyValue(ruleName);
}
Copy the code

259. Go to full screen

function launchFullscreen(element) {
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen();
  }
}

launchFullscreen(document.documentElement);
launchFullscreen(document.getElementById("id")); // An element goes to full screen
Copy the code

260 Exit full screen

function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
}

exitFullscreen();
Copy the code

261 Full screen events

document.addEventListener("fullscreenchange".function (e) {
  if (document.fullscreenElement) {
    console.log("Go full screen");
  } else {
    console.log("Exit full screen"); }});Copy the code

Digital Number

262. Digit thousandths split

function commafy(num) {
  return num.toString().indexOf(".")! = =- 1
    ? num.toLocaleString()
    : num.toString().replace(/(\d)(? = (? :\d{3})+$)/g."$1");
}
commafy(1000)
Copy the code

263. Generate random numbers

function randomNum(min, max) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * min + 1.10);
    case 2:
      return parseInt(Math.random() * (max - min + 1) + min, 10);
    default:
      return 0;
  }
}
randomNum(1.10)
Copy the code

264 Timestamp transfer time

/* Timestamp to time */
function timestampToTime(cjsj) {
	var date = new Date(cjsj); // If the timestamp is 10 digits, the timestamp is multiplied by 1000. If the timestamp is 13 digits, the timestamp is not multiplied by 1000
	var Y = date.getFullYear() + The '-';
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + The '-';
	var D = (date.getDate() + 1 < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
	return Y + M + D
}
Copy the code

265 Filters rich text and Spaces to plain text

/* Filter rich text and Spaces for plain text */
function filterHtml(str) {
	return str.replace(/<[^<>]+>/g.' ').replace(/  /ig.' ');
}
Copy the code

266 If the number of characters displayed is unnecessary, use ellipsis instead

/* Specifies the number of characters to display
function strEllp(str, num = str.length) {
	var subStr = str.substring(0, num);
	return subStr + (str.length > num ? '... ' : ' ');
}
Copy the code

267 Gets the current position of the scroll bar

// Get the current position of the scroll bar
function getScrollTop() {
	var scrollTop = 0
	if (document.documentElement && document.documentElement.scrollTop) {
		scrollTop = document.documentElement.scrollTop;
	} else if (document.body) {
		scrollTop = document.body.scrollTop;
	}
	return scrollTop
}
Copy the code

268 Gets the height of the current viewing range

// Get the height of the current viewable range
function getClientHeight() {
	var clientHeight = 0
	if (document.body.clientHeight && document.documentElement.clientHeight) {
		clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight)
	} else {
		clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight)
	}
	return clientHeight
}
Copy the code

269 Get the full height of the document

// Get the full height of the document
function getScrollHeight() {
	return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
}
Copy the code

If this article helps you, please like it and follow it, search for “Call me Jayne hide and Hide” and join our technology group to learn and discuss and explore the frontier together.