This article refers to the original text- http://bjbsair.com/2020-03-22/tech-info/2077/
JavaScript is currently one of the most popular programming languages, as most people say: "If you want to learn a programming language, learn JavaScript."
Quincy Larson, the founder of FreeCodeCamp, was asked in a recent interview which language developers should learn first.He replies, "JavaScript.":
"Software is eating the world, and JavaScript is eating software.JavaScript is becoming more and more dominant every year, and no one knows what will eventually replace it."If you don't have a good reason to learn a new language (for example, your job requires you to maintain a non-JavaScript code base), my recommendation is to focus on improving JavaScript."
You're not very excited to hear so much.Here are 127 common JS code snippets for you to learn and use.
1,all
Returns true if all elements of the array satisfy the function condition.When called, if the second parameter is omitted, the Boolean value is passed by default.
const all = (arr, fn = Boolean) => arr.every(fn); all([4, 2, 3], x => x > 1); // true all([1, 2, 3]); // true copy code
2,allEqual
Determine if the elements in the array are all equal
const allEqual = arr => arr.every(val => val === arr[0]); allEqual([1, 2, 3, 4, 5, 6]); // false allEqual([1, 1, 1, 1]); // true copy code
3,approximatelyEqual
This code sample checks whether two numbers are approximately equal, and the difference values can be set by passing parameters
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon; approximatelyEqual(Math.PI / 2.0, 1.5708); // true copy code
4,arrayToCSV
This code converts elements without commas or double quotes to strings with comma delimiters, which are recognized as CSV formats.
const arrayToCSV = (arr, delimiter = ',') => arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n'); arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"' arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // ''a';'b'\n'c';'d''copy code
5,arrayToHtmlList
This code converts an array element into a <li>tag and adds this element to the given ID element tag.
const arrayToHtmlList = (arr, listID) => (el => ( (el = document.querySelector('#' + listID)), (el.innerHTML += arr.map(item => `<li>${item}</li>`).join('')) ))(); arrayToHtmlList(['item 1', 'item 2'], 'myListID');Copy Code
6,attempt
This code executes a function, returns the remaining parameters back to the function as parameters, returns the corresponding results, and can catch exceptions.
const attempt = (fn, ...args) => { try { return fn(...args); } catch (e) { return e instanceof Error ? e : new Error(e); } }; var elements = attempt(function(selector) { return document.querySelectorAll(selector); }, '>_>'); if (elements instanceof Error) elements = []; // elements = [] Copy Code
7,average
This code returns the average of two or more numbers.
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length; average(...[1, 2, 3]); // 2 average(1, 2, 3); // 2 Copy code
8,averageBy
An example of a combination of the map() and reduce() functions that first converts objects into arrays through the map() function, then adds them up by calling the reduce() function, then returns the average based on the length of the array.
const averageBy = (arr, fn) => arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / arr.length; averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5 averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5 Copy code
9,bifurcate
This function contains two parameters, each of which is an array. The array of one parameter is grouped according to the true or false condition of the second parameter, if it is placed in the first array and the other in the second.A combination of Array.prototype.reduce() and Array.prototype.push() is used here.
const bifurcate = (arr, filter) => arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]); bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [['beep','boop','bar'], ['foo']] Copy the code
10,bifurcateBy
This code groups the arrays according to the specified function logic. The logic that satisfies the function condition is true, and the other unsatisfactory arrays are placed in the second array.Array.prototype.reduce() is combined with Array.prototype.push(), which is added to the array through the Array.prototype.push() function based on the function filtering logic.
const bifurcateBy = (arr, fn) => arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]); bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [['beep','boop','bar'], ['foo']] Copy the code
11,bottomVisible
Used to detect whether a page scrolls to the bottom of the page.
const bottomVisible = () => document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight); bottomVisible(); // true copy code
12,byteSize
This code returns the byte length of the string.Blob objects are used here, and Blob (Binary Large Object) objects represent a piece of binary data and provide a series of operation interfaces.Other API s for manipulating binary data, such as File objects, are built on Blob objects and inherit their properties and methods.There are two ways to generate blob objects: one by using the Blob constructor and the other by slicing out a portion of an existing blob object.
const byteSize = str => new Blob([str]).size; byteSize(''); // 4 byteSize('Hello World'); // 11 Copy code
13,capitalize
Converts the first letter of a string to uppercase, which mainly applies to the use of the ES6 expansion syntax in arrays.
const capitalize = ([first, ...rest]) => first.toUpperCase() + rest.join(''); capitalize('fooBar'); // 'FooBar' capitalize('fooBar', true); // 'FooBar'Copy Code
14,capitalizeEveryWord
Converts the first letter of each word in a sentence to uppercase, where regular expressions are used to replace it.
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); capitalizeEveryWord('hello world!'); // 'Hello World!'Copy Code
15,castArray
This code converts a non-numeric value into an array object.
const castArray = val => (Array.isArray(val) ? val : [val]); castArray('foo'); // ['foo'] castArray([1]); // [1] Copy code
16,compact
Remove the contents of the array that have a value of false.
const compact = arr => arr.filter(Boolean); compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [1, 2, 3,'a','s', 34] Copy code
17,countOccurrences
Count the number of occurrences of a value in an array
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3 Copy code
18,Create Directory
This snippet uses existSync() to check for the existence of a directory, and then uses mkdirSync() to create a directory if it does not exist.
const fs = require('fs'); const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined); createDirIfNotExists('test'); // Create the directory'test', if it does't exist copy code
19,currentURL
Returns the URL address currently accessed.
const currentURL = () => window.location.href; currentURL(); // 'https://medium.com/@fatosmorina'Copy Code
20,dayOfYear
Return to the current day of the year
const dayOfYear = date => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); dayOfYear(new Date()); // 272 Copy Code
21,decapitalize
Converts the first letter of a string to lowercase
const decapitalize = ([first, ...rest]) => first.toLowerCase() + rest.join('') decapitalize('FooBar'); // 'fooBar'
22,deepFlatten
Multidimensional arrays are flattened into one-dimensional arrays in a recursive form.
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); deepFlatten([1, [2], [[3], 4], 5]); // Copy Code [1,2,3,4,5]
23,default
If the object contains duplicate attributes, the previous one will prevail.
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // {a: 1, b: 2} Copy Code
24,defer
Delay function call, that is, call function asynchronously.
const defer = (fn, ...args) => setTimeout(fn, 1, ...args); defer(console.log, 'a'), console.log('b'); // Logs'b'then'a' copy code
25,degreesToRads
This code converts standard degrees into radians.
const degreesToRads = deg => (deg * Math.PI) / 180.0; degreesToRads(90.0); // ~1.5708 Copy Code
26,difference
This code looks for the difference between two given arrays and finds that the former array has no elements in the latter.
const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; difference([1, 2, 3], [1, 2, 4]); // [3] Copy Code
27,differenceBy
Processing an array requiring comparison of differences through a given function finds that the former array has no elements in the latter.
const differenceBy = (a, b, fn) => { const s = new Set(b.map(fn)); return a.filter(x => !s.has(fn(x))); }; differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2] differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [{x: 2}] Copy Code
28,differenceWith
This code filters the arrays that need to be compared according to the given function logic to find out that the former array has no elements in the latter.
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // Copy Code [1, 1.2]
29,digitize
Split the input number into an array of individual numbers.
const digitize = n => [...`${n}`].map(i => parseInt(i)); digitize(431); // Copy Code [4, 3, 1]
30,distance
Calculate the distance between two points
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); distance(1, 1, 2, 3); // 2.23606797749979 Copy Code
31,drop
This code deletes n elements from the left of a given array
const drop = (arr, n = 1) => arr.slice(n); drop([1, 2, 3]); // [2,3] drop([1, 2, 3], 2); // [3] drop([1, 2, 3], 42); // [] Copy code
32,dropRight
This code deletes n elements from the right of a given array
const dropRight = (arr, n = 1) => arr.slice(0, -n); dropRight([1, 2, 3]); // [1,2] dropRight([1, 2, 3], 2); // [1] dropRight([1, 2, 3], 42); // [] Copy code
33,dropRightWhile
This code deletes the given array from the right according to the given function condition until the current element meets the function condition True, stops deleting, and returns the remaining elements of the array.
const dropRightWhile = (arr, func) => { while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1); return arr; }; dropRightWhile([1, 2, 3, 4], n => n < 3); // Copy Code [1, 2]
34,dropWhile
The array is filtered according to the given function conditions, and those that do not meet the function conditions are removed from the array.
const dropWhile = (arr, func) => { while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); return arr; }; dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4] Copy Code
35,elementContains
Receives two DOM element object parameters to determine if the latter is a child of the former.
const elementContains = (parent, child) => parent !== child && parent.contains(child); elementContains(document.querySelector('head'), document.querySelector('title')); // true elementContains(document.querySelector('body'), document.querySelector('body')); // false copy code
36,filterNonUnique
Remove duplicate elements from the array
const filterNonUnique = arr => [ ...new Set(arr)]; filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // Copy Code [1, 2, 3, 4, 5]
37,findKey
Finds the key value of the first object that satisfies the given function condition.
const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj)); findKey( { barney: { age: 36, active: true }, fred: { age: 40, active: false }, pebbles: { age: 1, active: true } }, o => o['active'] ); // 'barney'copy code
38,findLast
Filter the array according to the given function condition, deleting the last element that meets the condition.
const findLast = (arr, fn) => arr.filter(fn).pop(); findLast([1, 2, 3, 4], n => n % 2 === 1); // 3 Copy code
39,flatten
Flattens a nested array according to the depth of the specified array.
const flatten = (arr, depth = 1) => arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []); flatten([1, [2], 3, 4]); // [1, 2, 3, 4] flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8] Copy Code
40,forEachRight
Executes in turn from the right to the left of the array according to the given function condition.
const forEachRight = (arr, callback) => arr .slice(0) .reverse() .forEach(callback); forEachRight([1, 2, 3, 4], val => console.log(val)); // Copy Code'4','3','2','1'
41,forOwn
This code iterates over objects using three parameters as inputs (values, keys, objects themselves) according to a given function condition.
const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj)); forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1 copy code
42,functionName
The name of this code output function.
const functionName = fn => (console.debug(fn.name), fn); functionName(Math.max); // max (logged in debug channel of console)
43,getColonTimeFromDate
This code gets the current time from the Date object.
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8); getColonTimeFromDate(new Date()); // "08:38:00" copy code
44,getDaysDiffBetweenDates
This code returns the difference between two dates by how many days
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); getDaysDiffBetweenDates(new Date('2019-01-13'), new Date('2019-01-15')); // 2 Copy code
45,getStyle
This code returns the attribute value corresponding to the DOM element node.
const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; getStyle(document.querySelector('p'), 'font-size'); // '16px'copy code
46,getType
The main function of this code is to return the type of data.
const getType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); getType(new Set([1, 2, 3])); // 'set'copy code
47,hasClass
This code returns whether the DOM element contains the specified Class style.
const hasClass = (el, className) => el.classList.contains(className); hasClass(document.querySelector('p.special'), 'special'); // true copy code
48,head
This code outputs the first element of the array.
const head = arr => arr[0]; head([1, 2, 3]); // 1 Copy code
49,hide
This code hides the specified DOM element.
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none')); hide(document.querySelectorAll('img')); // Hides all <img> elements on the page copy code
50,httpsRedirect
The function of this code is to redirect the http web address to the https web address.
const httpsRedirect = () => { if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); }; httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com Copy Code
51,indexOfAll
This code returns all index values corresponding to a value in the array, or an empty array if it is not included.
const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []); indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3] indexOfAll([1, 2, 3], 4); // [] Copy code
52,initial
This code returns all elements of the array except the last element
const initial = arr => arr.slice(0, -1); initial([1, 2, 3]); // [1,2]const initial = arr => arr.slice(0, -1); initial([1, 2, 3]); // [1,2] Copy Code
53,insertAfter
The main function of this code is to insert new node content after a given DOM node
const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString); insertAfter(document.getElementById('myId'), '<p>after</p>'); // <div id="myId">...</div> <p>after</p>Copy code
54,insertBefore
The main function of this code is to insert new node content before a given DOM node
const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString); insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId"> </div>Copy code
55,intersection
This code returns the intersection between two array elements.
const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); }; intersection([1, 2, 3], [4, 3, 2]); // [2, 3] Copy Code
56,intersectionBy
Processes the array elements that need to be compared according to the given function, then finds the intersection based on the processed array, and outputs the corresponding elements from the first array.
const intersectionBy = (a, b, fn) => { const s = new Set(b.map(fn)); return a.filter(x => s.has(fn(x))); }; intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1] Copy Code
57,intersectionBy
Compare the differences between the two arrays according to the given function, find the intersection, and output the corresponding elements from the first array.
const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // Copy Code [1.5, 3, 0]
58,is
This code is used to determine if the data is of the specified data type and returns true if it is.
const is = (type, val) => ![, null].includes(val) && val.constructor === type; is(Array, [1]); // true is(ArrayBuffer, new ArrayBuffer()); // true is(Map, new Map()); // true is(RegExp, /./g); // true is(Set, new Set()); // true is(WeakMap, new WeakMap()); // true is(WeakSet, new WeakSet()); // true is(String, ''); // true is(String, new String('')); // true is(Number, 1); // true is(Number, new Number(1)); // true is(Boolean, true); // true is(Boolean, new Boolean(true)); // true copy code
59,isAfterDate
Receives parameters of two date types to determine whether the former date is later than the latter.
const isAfterDate = (dateA, dateB) => dateA > dateB; isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true copy code
60,isAnagram
Used to detect whether two words are similar.
const isAnagram = (str1, str2) => { const normalize = str => str .toLowerCase() .replace(/[^a-z0-9]/gi, '') .split('') .sort() .join(''); return normalize(str1) === normalize(str2); }; isAnagram('iceman', 'cinema'); // true copy code
61,isArrayLike
This code detects if the object is a class array object and is iterative.
const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function'; isArrayLike(document.querySelectorAll('.className')); // true isArrayLike('abc'); // true isArrayLike(null); // false copy code
62,isBeforeDate
Receives parameters of two date types to determine whether the former date is earlier than the latter.
const isBeforeDate = (dateA, dateB) => dateA < dateB; isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true copy code
63,isBoolean
This code checks to see if the parameter is of Boolean type.
const isBoolean = val => typeof val === 'boolean'; isBoolean(null); // false isBoolean(false); // true
64,getColonTimeFromDate
Used to determine if the program runs in a browser environment, which helps avoid errors when running front-end modules in a node environment.
const isBrowser = () => ![typeof window, typeof document].includes('undefined'); isBrowser(); // true (browser) isBrowser(); // false (Node) copy code
65,isBrowserTabFocused
Used to determine if the current page is active (display).
const isBrowserTabFocused = () => !document.hidden; isBrowserTabFocused(); // true copy code
66,isLowerCase
Used to determine if the current string is all lowercase.
const isLowerCase = str => str === str.toLowerCase(); isLowerCase('abc'); // true isLowerCase('a3@$'); // true isLowerCase('Ab4'); // false copy code
67,isNil
Used to determine if the value of the current variable is null or undefined.
const isNil = val => val === undefined || val === null; isNil(null); // true isNil(undefined); // true copy code
68,isNull
Used to determine if the value of the current variable is null type.
const isNull = val => val === null; isNull(null); // true copy code
69,isNumber
Used to check if the current value is of numeric type.
function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } isNumber('1'); // false isNumber(1); // true copy code
70,isObject
To determine whether the value of a parameter is an object, an Object constructor is used to create an object wrapper that returns the original value if it is an object type.
const isObject = obj => obj === Object(obj); isObject([1, 2, 3, 4]); // true isObject([]); // true isObject(['Hello!']); // true isObject({ a: 1 }); // true isObject({}); // true isObject(true); // false copy code
71,isObjectLike
Used to check whether the value of a parameter is null and the type is an object.
const isObjectLike = val => val !== null && typeof val === 'object'; isObjectLike({}); // true isObjectLike([1, 2, 3]); // true isObjectLike(x => x); // false isObjectLike(null); // false copy code
72,isPlainObject
This snippet checks whether the value of a parameter is an object created by an Object constructor.
const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object; isPlainObject({ a: 1 }); // true isPlainObject(new Map()); // false copy code
73,isPromiseLike
Used to check if the current object resembles a Promise function.
const isPromiseLike = obj => obj !== null && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; isPromiseLike({ then: function() { return ''; } }); // true isPromiseLike(null); // false isPromiseLike({}); // false copy code
74,isSameDate
Used to determine whether two given dates are the same day.
const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString(); isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true copy code
75,isString
Used to check if the current value is of string type.
const isString = val => typeof val === 'string'; isString('10'); // true copy code
76,isSymbol
Used to determine if the value of a parameter is of type Symbol.
const isSymbol = val => typeof val === 'symbol'; isSymbol(Symbol('x')); // true copy code
77,isUndefined
Used to determine if the type of the parameter is Undefined.
const isUndefined = val => val === undefined; isUndefined(undefined); // true copy code
78,isUpperCase
Used to determine if the current string is all uppercase.
const isUpperCase = str => str === str.toUpperCase(); isUpperCase('ABC'); // true isLowerCase('A3@$'); // true isLowerCase('aB4'); // false copy code
79,isValidJSON
Used to determine if a given string is a JSON string.
const isValidJSON = str => { try { JSON.parse(str); return true; } catch (e) { return false; } }; isValidJSON('{"name":"Adam","age":20}'); // true isValidJSON('{"name":"Adam",age:"20"}'); // false isValidJSON(null); // true copy code
80,last
This function returns the last element of the array.
const last = arr => arr[arr.length - 1]; last([1, 2, 3]); // 3 Copy code
81,matches
This function is used to compare two objects to determine if the first object contains the same attributes and values as the second object.
onst matches = (obj, source) => Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]); matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false copy code
82,maxDate
This code snippet looks for the largest date in the date array to output.
const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates)); const array = [ new Date(2017, 4, 13), new Date(2018, 2, 12), new Date(2016, 0, 10), new Date(2016, 0, 9) ]; maxDate(array); // 2018-03-11T22:00:00.000Z Copy Code
83,maxN
The maximum number of first n bits in the output array of this code.
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); maxN([1, 2, 3]); // [3] maxN([1, 2, 3], 2); // [3,2] Copy Code
84,minDate
This code snippet looks for the earliest date in the date array to output.
const minDate = (...dates) => new Date(Math.min.apply(null, ...dates)); const array = [ new Date(2017, 4, 13), new Date(2018, 2, 12), new Date(2016, 0, 10), new Date(2016, 0, 9) ]; minDate(array); // 2016-01-08T22:00:00.000Z
Subsection
Today's content is shared with you here. Thank you for your reading. If you like my sharing, please pay attention and forward a compliment. Your support is the driving force for me to share. We will continue to share the remaining code snippets in the future. Welcome to keep following.Not finished