一些有用的JS 代码片段
数组平均数
使用reduce()将每个值添加到累加器,初始值为0,总和除以数组长度。
const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
// average([1,2,3]) -> 2
注:reduce函数是求数组的和,具体参考 这里
英文大写
使用replace()匹配每个单词的第一个字符,并使用toUpperCase()来将其大写。
const capitalizeEveryWord = str => str.replace(/[a-z]/g, char => char.toUpperCase());
// capitalizeEveryWord('hello world!') -> 'Hello World!'
首字母大写
使用slice(0,1)和toUpperCase()大写第一个字母,slice(1)获取字符串的其余部分。 省略lowerRest参数以保持字符串的其余部分不变,或将其设置为true以转换为小写。
const capitalize = (str, lowerRest = false) => str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
// capitalize('myName', true) -> 'Myname'
// true:首字母大写的同事,首字母大写转换文小写。false:只是首字母大写
数组中特定值的出现次数
每次遇到数组中的特定值时,使用reduce()来递增计数器。
const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
// countOccurrences([1,1,2,1,2,3], 1) -> 3
当前URL
使用window.location.href来获取当前URL。
const currentUrl = _ => window.location.href;
// currentUrl() -> 'https://google.com'
递归
使用递归。如果提供的参数(args)数量足够,则调用传递函数f,否则返回一个curried函数f。
const curry = (fn, arity = fn.length, ...args) =>
arity <= args.length
? fn(...args)
: curry.bind(null, fn, arity, ...args);
// curry(Math.pow)(2)(10) -> 1024
// curry(Math.min, 3)(10)(50)(2) -> 2
数组的交集
从b创建一个Set,然后在a上使用Array.filter(),只保留b中不包含的值。
const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); };
// difference([1,2,3], [1,2]) -> [3]
两点之间的距离
使用Math.hypot()计算两点之间的欧几里德距离。
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
// distance(1,1, 2,3) -> 2.23606797749979
判断是否可以整除
使用模运算符(%)来检查余数是否等于0。
const isDivisible = (dividend, divisor) => dividend % divisor === 0;
// isDivisible(6,3) -> true
转义正则表达式
使用replace()来转义特殊字符。
const escapeRegExp = str => str.replace(/[.*+?^${}()|[]]/g, '$&');
// escapeRegExp('(test)') -> (test)
偶数或奇数
使用Math.abs()将逻辑扩展为负数,使用模(%)运算符进行检查。 如果数字是偶数,则返回true;如果数字是奇数,则返回false。
const isEven = num => num % 2 === 0;
// isEven(3) -> false
阶乘
使用递归。如果n小于或等于1,则返回1。否则返回n和n - 1的阶乘的乘积。
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
// factorial(6) -> 720
查找数组中的唯一值
将Array.filter()用于仅包含唯一值的数组。
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]
Flatten数组
使用reduce()来获取数组中的所有元素,并使用concat()来使它们flatten。
const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
// flatten([1,[2],3,4]) -> [1,2,3,4]
从数组中获取最大值
使用Math.max()与spread运算符(...)结合得到数组中的最大值。
const arrayMax = arr => Math.max(...arr);
// arrayMax([10, 1, 5]) -> 10
从数组中获取最小值
使用Math.min()与spread`运算符(...)结合得到数组中的最小值。
const arrayMin = arr => Math.min(...arr);
// arrayMin([10, 1, 5]) -> 1
获取滚动位置
如果已定义,请使用pageXOffset和pageYOffset,否则使用scrollLeft和scrollTop,可以省略el来使用window的默认值。
const getScrollPos = (el = window) =>
({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});
// getScrollPos() -> {x: 0, y: 200}
最大公约数(GCD)
使用递归。基本情况是当y等于0时。在这种情况下,返回x。否则,返回y的GCD和x / y的其余部分。
const gcd = (x, y) => !y ? x : gcd(y, x % y);
// gcd (8, 36) -> 4
数组的末尾值
返回arr.slice(-1)[0]
const last = arr => arr.slice(-1)[0];
// last([1,2,3]) -> 3
测试功能所花费的时间
使用performance.now()获取函数的开始和结束时间,console.log()所花费的时间。第一个参数是函数名,随后的参数传递给函数。
const timeTaken = callback => {
console.time('timeTaken');
const r = callback();
console.timeEnd('timeTaken');
return r;
};
// timeTaken(() => Math.pow(2, 10)) -> 1024
// (logged): timeTaken: 0.02099609375ms
范围内的随机整数
使用Math.random()生成一个随机数并将其映射到所需的范围,使用Math.floor()使其成为一个整数。
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
// randomIntegerInRange(0, 5) -> 2
范围内的随机数
使用Math.random()生成一个随机值,使用乘法将其映射到所需的范围。
const randomInRange = (min, max) => Math.random() * (max - min) + min;
// randomInRange(2,10) -> 6.0211363285087005
重定向到URL
使用window.location.href或window.location.replace()重定向到url。 传递第二个参数来模拟链接点击(true - default)或HTTP重定向(false)。
const redirect = (url, asLink = true) =>
asLink ? window.location.href = url : window.location.replace(url);
// redirect('https://google.com')
反转一个字符串
使用数组解构和Array.reverse()来颠倒字符串中的字符顺序。合并字符以使用join('')获取字符串。
const reverseString = str => [...str].reverse().join('');
// reverseString('foobar') -> 'raboof'
RGB到十六进制
使用按位左移运算符(<<)和toString(16),然后padStart(6,“0”)将给定的RGB参数转换为十六进制字符串以获得6位十六进制值。
const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
// rgbToHex(255, 165, 1) -> 'ffa501'
滚动到顶部
使用document.documentElement.scrollTop 或 document.body.scrollTop获取到顶部的距离。
从顶部滚动一小部分距离。
使用window.requestAnimationFrame()来滚动。
const scrollToTop = _ => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
// scrollToTop()
按字符串排序(按字母顺序排列)
使用split('')分割字符串,sort()使用localeCompare(),使用join('')重新组合。
const sortCharactersInString = str =>
str.split('').sort((a, b) => a.localeCompare(b)).join('');
// sortCharactersInString('cabbage') -> 'aabbceg'
数组总和
使用reduce()将每个值添加到累加器,初始化值为0。
const sum = arr => arr.reduce((acc, val) => acc + val, 0);
// sum([1,2,3,4]) -> 10
数组唯一值
使用ES6 Set和... rest操作符去掉所有重复值。
const unique = arr => [...new Set(arr)];
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
URL参数
使用match()与适当的正则表达式来获得所有键值对,适当的map() 。使用Object.assign()和spread运算符(...)将所有键值对组合到一个对象中,将location.search作为参数传递给当前url。
const getUrlParameters = url =>
url.match(/([^?=&]+)(=([^&]*))/g).reduce(
(a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {}
);
// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
UUID生成器
使用crypto API生成符合RFC4122版本4的UUID。
const uuid = _ =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
验证数字
使用!isNaN和parseFloat()来检查参数是否是一个数字,使用isFinite()来检查数字是否是有限的。
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
// validateNumber('10') -> true
```~