判断当前代码运行环境
const isBrowser = typeof window === 'object' && typeof document === 'object';
清除所有Cookies
const clearCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)));
颜色转换
const toFullHexColor = (color) =>
`#${(color.startsWith('#') ? color.slice(1) : color)
.split('')
.map((c) => `${c}${c}`)
.join('')}`;
toFullHexColor('123'); // '#112233'
toFullHexColor('#123'); // '#112233'
toFullHexColor('#abc'); // '#aabbcc'
将Cookie转为对象
const cookies = document.cookie
.split(';')
.map((item) => item.split('='))
.reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});
将URL参数转为对象
const getUrlParams = (query) => Array.from(new URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }), {});
getUrlParams(location.search); // Get the parameters of the current URL
getUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }
// Duplicate key
getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }
对JWT进行反编译
const decode = (token) =>
decodeURIComponent(
atob(token.split('.')[1].replace('-', '+').replace('_', '/'))
.split('')
.map((c) => `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`)
.join('')
);
decode(`
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0I
joxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c);
// { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
判断是否是暗黑模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
对URL编码处理
// `encodeURIComponent` doesn't encode -_.!~*'()
const encode = (url) => encodeURIComponent(url).replace(/!/g, '%21').replace(/~/g, '%7E').replace(/\*/g, '%2A').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%20/g, '+');
创建一个产生唯一id的函数
const uid = (() => ((id = 0), () => id++))();
uid(); // 0
uid(); // 1
uid(); // 2
uid(); // 3
在Cookie中根据key得到value
const cookie = (name) => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga'); // GA1.2.825309271.1581874719
Get the value of a param from a URL
const getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param);
getParam('http://domain.com?message=hello', 'message'); // 'hello'
Get type of a variable in string 数据类型判断★
const getTypeOf = (obj) => Object.prototype.toString.call(obj).match(/\[object (.*)\]/)[1];
getTypeOf('hello world'); // String
getTypeOf(1000); // Number
getTypeOf(Infinity); // Number
getTypeOf(true); // Boolean
getTypeOf(Symbol()); // Symbol
getTypeOf(null); // Null
getTypeOf(undefined); // Undefined
getTypeOf({}); // Object
getTypeOf([]); // Array
getTypeOf(/[a-z]/g); // RegExp
getTypeOf(new Date(2021)); // Date
getTypeOf(new Error()); // Error
getTypeOf(function () {}); // Function
getTypeOf((a, b) => a + b); // Function
getTypeOf(async () => {}); // AsyncFunction
getTypeOf(document); // HTMLDocument
Swap two variables 替换变量
[a, b] = [b, a];
// Or
a = [b, (b = a)][0];
// Or
a = ((x) => x)(b, (b = a));
检查两个对象各自字段值是否相等
const isEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));
isEqual({ foo: 'bar' }, { foo: 'bar' }); // true
isEqual({ foo: 'bar' }, { bar: 'foo' }); // false
将二维数组转为对象
const toObj = (arr) => Object.fromEntries(arr);
// Or
const toObj = (arr) => arr.reduce((a, c) => ((a[c[0]] = c[1]), a), {});
toObj([
['a', 1],
['b', 2],
['c', 3],
]); // { a: 1, b: 2, c: 3 }
抽取对象数组中某个字段的所有值
const pluck = (objs, property) => objs.map((obj) => obj[property]);
pluck(
[
{ name: 'John', age: 20 },
{ name: 'Smith', age: 25 },
{ name: 'Peter', age: 30 },
],
'name'
); // ['John', 'Smith', 'Peter']
★去除有些对象的字段
const omit = (obj, keys) =>
Object.keys(obj)
.filter((k) => !keys.includes(k))
.reduce((res, k) => Object.assign(res, { [k]: obj[k] }), {});
omit({ a: '1', b: '2', c: '3' }, ['a', 'b']); // { c: '3' }
去除一个对象中所有的null和undefined
const removeNullUndefined = (obj) => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});
// Or
const removeNullUndefined = (obj) =>
Object.entries(obj)
.filter(([_, v]) => v != null)
.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});
removeNullUndefined({
foo: null,
bar: undefined,
fuzz: 42,
}); // { fuzz: 42 }
★★提取一个对象中某些属性值
const pick = (obj, keys) =>
Object.keys(obj)
.filter((k) => keys.includes(k))
.reduce((res, k) => Object.assign(res, { [k]: obj[k] }), {});
pick({ a: '1', b: '2', c: '3' }, ['a', 'b']); // { a: '1', b: '2' }
对象浅拷贝★
const shallowCopy = obj => Object.assign({}, obj);
// or
const shallowCopy = obj => {...obj};
Generate a random boolean 生成随机true或false
const randomBoolean = () => Math.random() >= 0.5;
生成指定范围内的随机数字
const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
生成指定长度的随机字符串
const generateString = (length, chars) =>
Array(length)
.fill('')
.map((v) => chars[Math.floor(Math.random() * chars.length)])
.join('');
generateString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
生成随机UUID
const uuid = (a) => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid));
Generate an array of random integers in a given range
randomArrayInRange(1, 100, 10); // [11, 82, 41, 35, 76, 83, 43, 15, 60, 54]
Generate a random sign (-1或1)
const randomSign = () => (Math.random() >= 0.5 ? 1 : -1);
https://1loc.dev/number/add-an-ordinal-suffix-to-a-number/
标签:const,杂七杂八,Object,getTypeOf,replace,obj,工具,foo,方法 From: https://www.cnblogs.com/openmind-ink/p/17124955.html