Array
遍历数组
[1, 2, 3].forEach((val, index) => console.log(val))
映射新数组
let arr = [1, 2, 3].map(v=>v*2)
所有元素是否通过测试
[1, 2, 3, 4].every(v=>v>3)
是否有元素通过测试
[1, 2, 3, 4].some(v=>v>3)
过滤数组
[1, 2, 3, 4, 5].filter(v=>v>3)
查找符合条件的元素
arr = [{ name: 'dashen', age: 18 }, { name: 'rom', age: 1 }]
连接数组
1 | let arr1 = [1, 2, 3]; |
数组去重
[...new Set(arr)]
通过数组取平均值
1 | const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length; |
数组切块
使用 Array.from() 创建一个满足块的数量的新的数组。
使用 Array.slice() 将新数组的每个元素映射到 size 长度的块。
如果原始数组不能均匀分割,最后的块将包含剩余的元素。1
2
3const chunk = (arr, size) =>
Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size));
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5]
压缩
使用 Array.filter() 去过滤掉假值(false, null, 0, “”, undefined 和 NaN)1
2const compact = (arr) => arr.filter(v => v);
// compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]
计算数组中指定值出现的次数
使用 Array.reduce() 去迭代数组,当值相同时,递增计数器。
1
2const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
// countOccurrences([1,1,2,1,2,3], 1) -> 3
深度展开数组
使用递归。
使用 Array.reduce() 获取所有不是数组的值,并将数组展开。1
2
3const deepFlatten = arr =>
arr.reduce((a, v) => a.concat(Array.isArray(v) ? deepFlatten(v) : v), []);
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
获取数组中的最大值
使用 Math.max() 配合 … 扩展运算符去获取数组中的最大值。
1
2const arrayMax = arr => Math.max(...arr);
// arrayMax([10, 1, 5]) -> 10
条件分组
使用 Array.map() 将数组的值映射到函数或属性名称。
使用 Array.reduce() 创建一个对象,其中的键是从映射的结果中产生的。
1
2
3
4
5const 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; }, {});
// groupBy([6.1, 4.2, 6.3], Math.floor) -> {4: [4.2], 6: [6.1, 6.3]}
// groupBy(['one', 'two', 'three'], 'length') -> {3: ['one', 'two'], 5: ['three']}
去除最后一个元素
1 | const initial = arr => arr.slice(0, -1); |
使用指定范围来定义数组
使用 Array(end-start) 创建一个所需长度的数组,使用 Array.map() 来填充范围中的所需值。
你可以省略start,默认值为 0。
1
2
3const initializeArrayRange = (end, start = 0) =>
Array.apply(null, Array(end - start)).map((v, i) => i + start);
// initializeArrayRange(5) -> [0,1,2,3,4]
使用指定值来定义数组
使用 Array(n) 创建一个所需长度的数组,使用 fill(v) 去填充所需要的值。
亦可以省略 value,默认值为 0。
1
2const initializeArray = (n, value = 0) => Array(n).fill(value);
// initializeArray(5, 2) -> [2,2,2,2,2]
获取数组的中间值
找到数组的中间,使用 Array.sort() 对值进行排序。
如果长度是奇数,则返回中点处的数字,否则返回两个中间数字的平均值。
1
2
3
4
5
6const median = arr => {
const mid = Math.floor(arr.length / 2), nums = arr.sort((a, b) => a - b);
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
};
// median([5,6,50,1,-5]) -> 5
// median([0,10,-2,7]) -> 3.5
获取数组的交集
使用 filter() 移除不是 values 的一部分的值,使用 includes() 确定。
1
2const similarity = (arr, values) => arr.filter(v => values.includes(v));
// similarity([1,2,3], [1,2,4]) -> [1,2]
数组的总和
使用 Array.reduce() 去迭代值并计算累计器,初始值为 0。
1
2const sum = arr => arr.reduce((acc, val) => acc + val, 0);
// sum([1,2,3,4]) -> 10
Object
获取对象的key
Object.keys({name:'a',age:1})
获取对象里数据的数量
Object.keys({name:'a',age:1}).length
遍历数组
Object.entries({name:'a',age:1})
extend
1 | const obj = {name:'a',age:1} |
键值对创建对象
1 | const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {}); |
对象生成键值对
1 | const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); |
浅拷贝对象
1 | const shallowClone = obj => ({ ...obj }); |
Function
链式异步函数
循环遍历包含异步事件的函数数组,当每个异步事件完成时调用 next。
1
2
3
4
5
6
7
8const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); };
/*
chainAsync([
next => { console.log('0 seconds'); setTimeout(next, 1000); },
next => { console.log('1 second'); setTimeout(next, 1000); },
next => { console.log('2 seconds'); }
])
*/
管道
使用 Array.reduce() 让值在函数间流通。
1
2const pipe = (...funcs) => arg => funcs.reduce((acc, func) => func(acc), arg);
// pipe(btoa, x => x.toUpperCase())("Test") -> "VGVZDA=="
promise转化
使用 currying 返回一个函数,返回一个调用原始函数的 Promise。
使用 …rest 运算符传入所有参数。
Node 8 版本以上,你可以使用 util.promisify1
2
3
4
5
6
7
8const promisify = func =>
(...args) =>
new Promise((resolve, reject) =>
func(...args, (err, result) =>
err ? reject(err) : resolve(result))
);
// const delay = promisify((d, cb) => setTimeout(cb, d))
// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
队列运行promise
使用 Array.reduce() 通过创建一个 promise 链来运行一系列 promise,每个 promise 在解析时返回下一个 promise。
1
2
3const series = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
// const delay = (d) => new Promise(r => setTimeout(r, d))
// series([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete
睡眠
通过返回一个 Promise 延迟执行 async 函数,把它放到睡眠状态。
1
2
3
4
5
6
7
8const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
/*
async function sleepyWork() {
console.log('I\'m going to sleep for 1 second.');
await sleep(1000);
console.log('I woke up after 1 second.');
}
*/
Math
考拉兹算法
如果 n 是偶数,返回 n/2,否则返回 3n+1
1
2
3const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1);
// collatz(8) --> 4
// collatz(5) --> 16
阶乘
1 | const factorial = n => n <= 1 ? 1 : n * factorial(n - 1); |
最大公约数(使用辗转相乘法)
使用递归。
基本情况是如果 y 等于 0,则返回 x。
其它情况下,返回 y 与 x/y 的最大公约数。1
2const gcd = (x, y) => !y ? x : gcd(y, x % y);
// gcd (8, 36) -> 4
百分位数
使用百分比公式计算给定数组中有多少个数小于或等于给定值。
使用Array.reduce()计算值的下面有多少个数是相同的值, 并应用百分比公式。1
2
3const percentile = (arr, val) =>
100 * arr.reduce((acc,v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length;
// percentile([1,2,3,4,5,6,7,8,9,10], 6) -> 55
取小数点后 n 位
使用 Math.round() 和字符串模板将数字四舍五入到指定的位数。
省略第二个参数,decimals 将四舍五入到一个整数。
1
2const round = (n, decimals=0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
// round(1.005, 2) -> 1.01
String
所有单词的第一个字母大写
1 | const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); |
单词的第一个字母大写
使用 slice(0,1) 和 toUpperCase() 将首字母大写,使用 slice(1) 得到字符串的其余部分。
忽略 lowerRest 参数以保持字符串的其余部分不变,或者将其设置为 true 以转换为小写字母。1
2
3const capitalize = (str, lowerRest = false) =>
str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
// capitalize('myName', true) -> 'Myname'
检查回文
使用 toLowerCase() 转换字符串并用 replace() 删除其中的非字母数字字符。
然后,使用 split(‘’) 分散为单个字符,再使用 reverse() 和 join(‘’) 倒序合并后与原字符进行比较。1
2
3
4
5const palindrome = str => {
const s = str.toLowerCase().replace(/[\W_]/g,'');
return s === s.split('').reverse().join('');
}
// palindrome('taco cat') -> true
字符串排序(按字母顺序排列)
使用 split(‘’) 切割字符串,使用 Array.sort 通过 localeCompare() 去排序,再使用 join(‘’) 组合。
1
2
3const sortCharactersInString = str =>
str.split('').sort((a, b) => a.localeCompare(b)).join('');
// sortCharactersInString('cabbage') -> 'aabbceg'
字符串截断
1 | const truncate = (str, num) => |
Media
语音合成(试验功能)
使用 SpeechSynthesisUtterance.voice 和 indow.speechSynthesis.getVoices() 将消息转换为语音。
使用 window.speechSynthesis.speak() 来播放消息。
了解更多API
Browser
底部可见即滚动至底部
使用 scrollY,scrollHeight 和 clientHeight 来确定页面的底部是否可见。
1
2
3const bottomVisible = _ =>
document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight);
// bottomVisible() -> true
当前链接地址
使用 window.location.href 来获取当前链接地址。
1
2const currentUrl = _ => window.location.href;
// currentUrl() -> 'https://google.com'
元素在视窗中可见
使用 Element.getBoundingClientRect() 和 window.inner(Width|Height) 值来确定给定的元素在视口中是否可见。
第二个参数用来指定元素是否要求完全可见,指定 true 即部分可见,默认为全部可见。
1
2
3
4
5
6
7
8
9
10const 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;
};
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
// elementIsVisibleInViewport(el) -> false (not fully visible)
// elementIsVisibleInViewport(el, true) -> true (partially visible)
获取滚动位置
如果存在,使用 pageXOffset 和 pageYOffset,否则使用 scrollLeft 和 scrollTop。
你可以省略 el,默认使用 window。
1
2
3
4const getScrollPos = (el = window) =>
({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});
// getScrollPos() -> {x: 0, y: 200}
URL 重定向
使用 window.location.href 或者 window.location.replace() 去重定向到 url。
第二个参数用来控制模拟链接点击(true - 默认)还是 HTTP 重定向(false)。
1
2
3const redirect = (url, asLink = true) =>
asLink ? window.location.href = url : window.location.replace(url);
// redirect('https://google.com')
滚动至顶部
使用 document.documentElement.scrollTop 或 document.body.scrollTop 获取到顶端的距离。
从顶部滚动一小部分距离。 使用 window.requestAnimationFrame() 实现滚动动画。
1
2
3
4
5
6
7
8const scrollToTop = _ => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
// scrollToTop()
Date
获取两个日期间的差距
计算两个 Date 对象之间的差距(以天为单位)。
1
2const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
// getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9
Utility
获取值的原始类型
返回值的构造函数名称的小写字符,值为 undefined 或 null 时则返回 undefined 或 null。1
2
3const getType = v =>
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
// getType(new Set([1,2,3])) -> "set"
测量函数的耗时
1 | const timeTaken = callback => { |
指定范围内的随机整数
使用 Math.random() 去生成一个在指定范围内的随机数,使用 Math.floor() 将其转换为整数。
1
2const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
// randomIntegerInRange(0, 5) -> 2
指定范围内的随机数
使用 Math.random() 去生成一个在指定范围内的随机数。
1
2const randomInRange = (min, max) => Math.random() * (max - min) + min;
// randomInRange(2,10) -> 6.0211363285087005
RGB转十六进制
使用按位左移运算符(<<)和 toString(16) 将 RGB 参数转换为十六进制,然后使用 padStart(6, ‘0’) 去获取6位数的十六进制。
1
2const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
// rgbToHex(255, 165, 1) -> 'ffa501'
交换两个变量的值
1 | [varA, varB] = [varB, varA]; |
URL参数
使用 match() 和一个合适的正则去获取所有键值对,使用 Array.reduce() 合并到一个对象中。
允许将 location.search 作为参数传递。
1
2
3
4
5const 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'}
值或默认值
默认返回 value 如果 value 为假,则返回默认值。
1
2const valueOrDefault = (value, d) => value || d;
// valueOrDefault(NaN, 30) -> 30