forObject
此代码片段遍历对象的每个属性,并分别为每个属性迭代一个回调。
const forObject = (obj, callback) =>
Object.keys(obj).forEach((key) => callback(obj[key], key, obj));
const testObj = {
title: "每天学习10个实用Javascript",
author: "天行无忌",
};
forObject(testObj, (val, key) => {
console.log(`${key}:${val}`);
});
// title:每天学习10个实用Javascript
// author:天行无忌
flatten
此代码片段使用递归将数组展平到指定的深度
const flatten = (array, depth = 1) =>
array.reduce(
(acc, current) =>
acc.concat(
depth > 1 && Array.isArray(current)
? flatten(current, depth - 1)
: current
),
[]
);
const arrayTest = [0, 1, 2, [[[3, 4, [5]]]]];
console.log(flatten(arrayTest)); // [ 0, 1, 2, [ [ 3, 4, [Array] ] ] ]
console.log(arrayTest.flat()); // [ 0, 1, 2, [ [ 3, 4, [Array] ] ] ]
const depth = 3;
console.log(flatten(arrayTest, depth)); // [ 0, 1, 2, 3, 4, [ 5 ] ]
console.log(arrayTest.flat(depth)); // [ 0, 1, 2, 3, 4, [ 5 ] ]
deepFlatten
此代码片段使用递归将数组全部展平,和上面的函数相比,此函数无需指定深度,全部展平。
const deepFlatten = (array) =>
[].concat(
...array.map((item) => (Array.isArray(item) ? deepFlatten(item) : item))
);
const arrayTest = [0, 1, 2, [[[3, 4, [5]]]]];
console.log(deepFlatten(arrayTest)); // [ 0, 1, 2, 3, 4, 5 ]
findKey
此代码片段通过键值查找对象,返回满足给定函数的第一个 key。
const findKey = (obj, fn) =>
Object.keys(obj).find((key) => fn(obj[key], key, obj));
const testObj = {
hballard: { age: 36 },
sguzman: { age: 40 },
plowe: { age: 32 },
};
console.log(findKey(testObj, (item) => item.age > 32)); // hballard
dropWhile
此代码片段从数组中删除元素,直到传递的函数返回 true 。即从数组第一个元素开始删除,直到删除的元素满足函数返回 true 就停止。
const dropWhile = (array, fn) => {
while (array.length > 0 && !fn(array[0])) array = array.slice(1);
return array;
};
const testArray = [30, 29, 33, 31, 28];
console.log(dropWhile(testArray, (item) => item >= 33)); // [ 33, 31, 28 ]
digitize
此代码片段将数字拆分为单个数字组成的数组,这个是扩展运算符 ... 的比较经典的使用方法。
const digitize = (number) => [...`${number}`].map((item) => parseInt(item));
console.log(digitize(2022)); // [ 2, 0, 2, 2 ]
随机 ID 生成器
以从当前时间(以毫秒为单位)或特定的整数和增量开始,也可以从字母数字字符生成ID。
// 创建从当前时间开始的唯一id(以毫秒为单位),每次请求时加1
const uniqueId = ((mil) => () => mil++)(Date.now());
// 创建指定长度的数字组成的唯一递增ID
const uniqueIncrementingId = ((numb) => (length = 12) =>
`${numb++}`.padStart(length, "0"))(1);
// 创建字母和数字组成的唯一 id
const uniqueAlphaNumericId = (() => {
const heyStack = "0123456789abcdefghijklmnopqrstuvwxyz";
const { length } = heyStack;
const randomInt = () => Math.floor(Math.random() * length);
return (length = 24) =>
Array.from({ length }, () => heyStack[randomInt()]).join("");
})();
console.log(uniqueId()); // 1633317380617
console.log(uniqueIncrementingId()); // 000000000001
console.log(uniqueIncrementingId()); // 000000000002
console.log(uniqueAlphaNumericId()); // e7r5y71cvfo18ccj1sgp70ts
找出总和、最小值和最大值
利用reduce方法来快速找到基本的数学运算
const array = [5,6,7,8,80,9];
1. 求和
array.reduce((a,b) => a+b);
// 输出: 115
2. 最大值
array.reduce((a,b) => a>b?a:b);
// 输出: 80
3.最小值
array.reduce((a,b) => a<b?a:b);
// 输出: 5
数组去重
您可能已经将 indexOf() 与 for 循环一起使用,该循环返回第一个找到的索引或较新的 includes() 从数组中返回布尔值 true/false 以找出/删除重复项。有两种更快的方法。
const array = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// 输出: [5, 4, 7, 8, 9, 2]
使用解构简单交换两值
let a = 5;
let b = 8;
[a,b] = [b,a]
[a,b]
// 输出
(2) [8, 5]