Javascript代码段合集

花30秒或者更短的时间就能理解的Javascript代码段
- 可以使用
Ctrl + F或者command + F搜索 - 代码段使用ES6编写,使用 Babel transpiler 保证兼容.
- 作者在持续更新传送门
目录
Array
arrayMaxarrayMinchunkcompactcountOccurrencesdeepFlattendifferencedistinctValuesOfArraydropElementseveryNthfilterNonUniqueflattenflattenDepthgroupByheadinitialinitializeArrayWithRangeinitializeArrayWithValuesintersectionlastmapObjectnthElementpickpullremovesampleshufflesimilaritysymmetricDifferencetailtaketakeRightunionwithoutzip
Browser
bottomVisiblecurrentURLelementIsVisibleInViewportgetScrollPositiongetURLParametersredirectscrollToTop
Date
Function
Math
arrayAveragearraySumcollatzdigitizedistancefactorialfibonaccigcdhammingDistanceisDivisibleisEvenlcmmedianpalindromepercentilepowersetrandomIntegerInRangerandomNumberInRangeroundstandardDeviation
Media
Node
Object
String
anagramscapitalizecapitalizeEveryWordescapeRegExpfromCamelCasereverseStringsortCharactersInStringtoCamelCasetruncateString
Utility
coalescecoalesceFactoryextendHexgetTypehexToRGBisArrayisBooleanisFunctionisNumberisStringisSymbolRGBToHextimeTakentoOrdinalSuffixUUIDGeneratorvalidateEmailvalidateNumber
Array
arrayMax
返回数组中的最大值.
使用 Math.max() 配合展开操作符 (...) 得到数组中的最大值.
1 | const arrayMax = arr => Math.max(...arr); |
arrayMin
返回数组中的最小值.
使用 Math.min() 配合展开操作符 (...) 得到数组中的最小值.
1 | const arrayMin = arr => Math.min(...arr); |
chunk
将一个数组分割成几个数组段.
使用 Array.from() 创建一个适合它长度的新的数组
使用 Array.slice() 分割为指定 size 长度的数组段
如果指定的数组不能被平均分割,最后的块将包含剩余的元素。
1 | const chunk = (arr, size) => |
compact
移除数组中的非真值
使用 Array.filter() 过滤非真值 (false, null, 0, "", undefined, 和 NaN).
1 | const compact = (arr) => arr.filter(Boolean); |
countOccurrences
计算元素出现的次数.
使用 Array.reduce() 计算指定元素在数组中出现的次数
1 | const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0); |
deepFlatten
深度降维
使用递归.
使用 Array.concat() 和一个空数组 ([]) 还有展开运算符 (...) 降维一个多维数组.
1 | const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); |
difference
返回两个数组的差集
创建一个 b 的 Set, 然后使用 Array.filter() 查找 a 中不包含 b的元素.
1 | const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; |
distinctValuesOfArray
返回数组中不重复的元素
使用 ES6的 Set 和展开运算符 ...rest 过滤重复的元素.
1 | const distinctValuesOfArray = arr => [...new Set(arr)]; |
dropElements
给函数传递一个表达式和数组,只保留表达式为true的元素
1 | const dropElements = (arr, func) => { |
everyNth
返回数组中每一个第n的元素.
使用 Array.filter() 返回每一个第n的元素.
1 | const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === 0); |
filterNonUnique
过滤不唯一的元素.
使用 Array.filter() 只保留唯一的元素.
1 | const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); |
flatten
降维数组.
使用 Array.reduce() 获取到每一个元素然后使用 concat() 降维.
1 | const flatten = arr => arr.reduce((a, v) => a.concat(v), []); |
flattenDepth
根据指定的深度降维数组.
使用递归,为所有维度的数组降低一维.
使用 Array.reduce() 和 Array.concat() 合并降维后的数组或元素.
此时如果 depth 为 1 停止递归.
1 | const flattenDepth = (arr, depth = 1) => |
groupBy
根据指定的表达式为数组分组
使用 Array.map() 映射为根据表达式或属性名值计算后的数组
使用 Array.reduce() 创建一个键值是上一步map出来的结果,值是相对应的数组的对象
1 | const groupBy = (arr, func) => |
head
返回集合的第一个元素
使用 arr[0] 返回给定数组的第一个元素.
1 | const head = arr => arr[0]; |
initial
返回一个数组中除去最后一个元素的其他元素.
使用 arr.slice(0,-1) 返回除去最后一个元素的其他元素.
1 | const initial = arr => arr.slice(0, -1); |
initializeArrayWithRange
初始化一个指定范围的数组
使用 Array(end-start) 创建一个期望长度的数组, 根据给定的范围使用Array.map()填充数组.
参数start 默认值为 0.
1 | const initializeArrayWithRange = (end, start = 0) => |
initializeArrayWithValues
初始化并且根据给定的值填充数组.
使用 Array(n) 创建一个期望长度的数组, 根据给定的值使用 fill(v) 填充数组.
参数 value 默认值为 0.
1 | const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value); |
intersection
返回两个数组的交集.
创建一个 b 的 Set, 然后使用 a 的 Array.filter() 查找含 b 元素.
1 | const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); }; |
last
返回数组中的最后一个元素.
使用 arr.length - 1 计算出最后一个元素的索引,然后返回它的值.
1 | const last = arr => arr[arr.length - 1]; |
mapObject
映射一个数组,结果是键值为他的每一个元素的值,值为给定表达式结果的对象
1 | const mapObject = (arr, fn) => |
nthElement
返回数组的第n个对象.
使用 Array.slice() 获取满足给定条件的数组的第一个元素
如果给定的索引超出范围,返回 [].
参数 n 默认为第一个元素
1 | const nthElement = (arr, n=0) => (n>0? arr.slice(n,n+1) : arr.slice(n))[0]; |
pick
返回对象的一个拷贝,返回的对象只含有给定的键的键值对
1 | const pick = (obj, arr) => |
pull
抽取数组中指定的元素
使用 Array.filter() 和 Array.includes() 抽出不需要的元素.
使用 Array.length = 0 重置数组并且使用 Array.push() 重新填充抽取后的数组.
1 | const pull = (arr, ...args) => { |
remove
移除数组中给定表达式为 false. 的值
使用 Array.filter() 找到表达式为 true 的值,然后通过 Array.reduce() 使用 Array.splice() 移除.
1 | const remove = (arr, func) => |
sample
返回数组的一个随机元素
使用 Math.random() 创建一个随机数,然后和 length 相乘之后通过 Math.floor() 找到一个最接近的数.
1 | const sample = arr => arr[Math.floor(Math.random() * arr.length)]; |
shuffle
打乱数组中值的顺序
使用 Array.sort() 重新排序, 使用 Math.random() - 0.5 作为compareFunction.
1 | const shuffle = arr => arr.sort(() => Math.random() - 0.5); |
similarity
返回一个数组,它的值两个数组里面都存在.
使用 includes() 找出values不含有的元素,使用filter()移除.
1 | const similarity = (arr, values) => arr.filter(v => values.includes(v)); |
symmetricDifference
返回两个数组的对称差异.
通过两个数组分别创建 Set, 然后使用 Array.filter() 找出不在另外一个集合中的元素.
1 | const symmetricDifference = (a, b) => { |
tail
返回数组中除去第一个元素的集合
如果数组length 大于 1, 返回 arr.slice(1) 否则就返回整个数组.
1 | const tail = arr => arr.length > 1 ? arr.slice(1) : arr; |
take
返回前n个元素.
1 | const take = (arr, n = 1) => arr.slice(0, n); |
takeRight
返回后n个元素.
1 | const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); |
union
合并两个集合(结果不含重复元素)
1 | const union = (a, b) => Array.from(new Set([...a, ...b])); |
without
根据指定的值过滤数组
1 | const without = (arr, ...args) => arr.filter(v => !args.includes(v)); |
zip
根据原始数组的位置把多个数组压缩
使用 Math.max.apply() 获取输入数组中最大的长度,根据这个长度使用Array.from()创建一个新的数组,之后把输入数组的映射压缩到里面,如果某个数组缺少元素使用undefined代替
1 | const zip = (...arrays) => { |
Browser
bottomVisible
如果到达页面底部,返回true否则返回false
使用 scrollY, scrollHeight 和 clientHeight 判断是否到达页面底部
1 | const bottomVisible = () => |
currentURL
返回当前页面的URL.
使用 window.location.href 获取当前页面URL.
1 | const currentURL = () => window.location.href; |
elementIsVisibleInViewport
如果一个元素在视口可见,返回true否则返回false
使用 Element.getBoundingClientRect() 和 window.inner(Width|Height) 判断元素是否在视口可见,第二个参数设置为true表示是否部分可见,默认值为false
1 | const elementIsVisibleInViewport = (el, partiallyVisible = false) => { |
getScrollPosition
返回滚动条在当前页面的位置.
如果 pageXOffset 和 pageYOffset 未定义,使用 scrollLeft and scrollTop.
1 | const getScrollPosition = (el = window) => |
getURLParameters
返回URL查询字符串对象.
1 | const getURLParameters = url => |
redirect
重定向到指定的URL.
1 | const redirect = (url, asLink = true) => |
scrollToTop
平滑滚动到页面顶部.
1 | const scrollToTop = () => { |
Date
getDaysDiffBetweenDates
返回两个Date对象的天数差
1 | const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); |
JSONToDate
转换一个JSON对象为时间.
1 | const JSONToDate = arr => { |
toEnglishDate
把美国时间转换为英国时间.
1 | const toEnglishDate = (time) => |
Function
chainAsync
串联异步方法.
1 | const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); }; |
compose
从右往左执行函数组合
1 | const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); |
curry
对函数进行柯里化
1 | const curry = (fn, arity = fn.length, ...args) => |
functionName
打印函数名称
1 | const functionName = fn => (console.debug(fn.name), fn); |
pipe
从左往右执行函数组合
1 | const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); |
promisify
把异步函数转化为promise
In Node 8+, you can use util.promisify
1 | const promisify = func => |
runPromisesInSeries
执行一系列promise函数
1 | const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); |
sleep
延迟执行异步函数
Delay executing part of an async function, by putting it to sleep, returning a Promise.
1 | const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); |
Math
arrayAverage
返回数组的平均值
1 | const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length; |
arraySum
返回数组的和
1 | const arraySum = arr => arr.reduce((acc, val) => acc + val, 0); |
collatz
实现Collatz算法.
如果 n 是偶数, 返回 n/2. 否则返回 3n+1.
1 | const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1); |
digitize
把数字转为数组
1 | const digitize = n => [...''+n].map(i => parseInt(i)); |
distance
返回两点距离.
1 | const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); |
factorial
计算一个数字的阶乘.
1 | const factorial = n => |
fibonacci
指定一个长度,输出斐波那契数列
1 | const fibonacci = n => |
gcd
计算两个数字之间的最大公约数。
1 | const gcd = (x, y) => !y ? x : gcd(y, x % y); |
hammingDistance
计算两个值的Hamming距离.
1 | const hammingDistance = (num1, num2) => |
isDivisible
检查第一个数字是否可被第二个数字整除.
1 | const isDivisible = (dividend, divisor) => dividend % divisor === 0; |
isEven
检查数字是否为偶数
1 | const isEven = num => num % 2 === 0; |
lcm
计算两个数字的最小公倍数.
1 | const lcm = (x,y) => { |
median
返回数组的中位数
1 | const median = arr => { |
palindrome
判断给定字符串是否是回文字符串(回文字符串是正读和反读都一样的字符串,比如“level”或者“noon”)
1 | const palindrome = str => { |
percentile
使用百分位数公式来计算给定数组中有多少数字小于或等于给定值。
1 | const percentile = (arr, val) => |
powerset
输出给定数组的所有子集
1 | const powerset = arr => |
randomIntegerInRange
返回指定范围内的随机整数
1 | const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; |
randomNumberInRange
返回指定范围内的随机数
1 | const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; |
round
将数字四舍五入到指定的数字位数.
1 | const round = (n, decimals=0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); |
standardDeviation
返回数组的标准差
1 | const standardDeviation = (arr, usePopulation = false) => { |
Media
speechSynthesis
语音合成 (实验特性).
详情查看 SpeechSynthesisUtterance interface of the Web Speech API.
1 | const speechSynthesis = message => { |
Node
JSONToFile
将一个JSON对象转换为文件.
1 | const fs = require('fs'); |
readFileLines
读取指定的文件并且根据行生成数组
1 | const fs = require('fs'); |
Object
cleanObj
移除对象中除去给定的属性名之外的属性
1 | const cleanObj = (obj, keysToKeep = [], childIndicator) => { |
objectFromPairs
根据给定的键值对生成对象
1 | const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {}); |
objectToPairs
转换一个对象为数组
1 | const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); |
shallowClone
创建一个对象的浅拷贝.
1 | const shallowClone = obj => Object.assign({}, obj); |
truthCheckCollection
检查某个属性名是否在一个数组中都存在
1 | truthCheckCollection = (collection, pre) => (collection.every(obj => obj[pre])); |
String
anagrams
生成一个字符串的所有字符排列组合(包含重复)
1 | const anagrams = str => { |
Capitalize
将给定字符串首字母大写.
1 | const capitalize = ([first,...rest], lowerRest = false) => |
capitalizeEveryWord
将给定字符串的每个单词首字母大写.
1 | const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); |
escapeRegExp
转义字符串以便在正则表达式中使用
1 | const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); |
fromCamelCase
把camelcase字符串转换成其他格式
1 | const fromCamelCase = (str, separator = '_') => |
reverseString
反转字符串
1 | const reverseString = str => [...str].reverse().join(''); |
sortCharactersInString
按照字母顺序重新排列字符串
1 | const sortCharactersInString = str => |
toCamelCase
把一个字符串转换为camelcase.
1 | const toCamelCase = str => |
truncateString
根据指定长度截取字符串
1 | const truncateString = (str, num) => |
Utility
coalesce
返回第一个不为null/undefined的参数
1 | const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)) |
coalesceFactory
实现自定义coalesce函数
1 | const coalesceFactory = valid => (...args) => args.find(valid); |
extendHex
将3位数的颜色代码扩展为6位数的颜色代码
1 | const extendHex = shortHex => |
getType
获取一个值的原生类型.
1 | const getType = v => |
hexToRGB
将hex色值转换为RGB
1 | const hexToRgb = hex => { |
isArray
检查给定对象是否是数组
1 | const isArray = val => !!val && Array.isArray(val); |
isBoolean
检查给定对象是否是布尔值
1 | const isBoolean = val => typeof val === 'boolean'; |
isFunction
检查给定对象是否是方法
1 | const isFunction = val => val && typeof val === 'function'; |
isNumber
检查给定对象是否是数字
1 | const isNumber = val => typeof val === 'number'; |
isString
检查给定对象是否是字符串
1 | const isString = val => typeof val === 'string'; |
isSymbol
检查给定对象是否是symbol.
1 | const isSymbol = val => typeof val === 'symbol'; |
RGBToHex
将RGB色值转换为Hex
1 | const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); |
timeTaken
计算函数执行时间
1 | const timeTaken = callback => { |
toOrdinalSuffix
Adds an ordinal suffix to a number.
Use the modulo operator (%) to find values of single and tens digits.
Find which ordinal pattern digits match.
If digit is found in teens pattern, use teens ordinal.
1 | const toOrdinalSuffix = num => { |
UUIDGenerator
生成UUID.
1 | const UUIDGenerator = () => |
validateEmail
验证是否为邮箱
1 | const validateEmail = str => |
validateNumber
验证是否为数字
1 | const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; |
Credits
Icons made by Smashicons from www.flaticon.com is licensed by CC 3.0 BY.