JavaScript单行代码 在项目中高效开发
- 1、生成随机字符串
- 2、获取两个数字之间的随机整数
- 3、字符串中每个单词的第一个字符大写
- 4、删除数组中的重复值
- 5、删除数组对象的重复值
- 6、展平一个数组
- 7、从数组中删除虚假值
- 8、检查一个数字是偶数还是奇数
- 9、获取参数的平均值
- 10、将数字保留固定小数点
- 11、计算两个日期相差天数
- 12、从日期中获取一年中的哪一天
- 13、生成一个随机的十六进制颜色
- 14、将RGB颜色转换为十六进制
- 15、清除所有cookies
- 16、检测暗模式
- 17、交换两个变量
- 18、暂停一会
1、生成随机字符串
我们可以使用 Math.random
生成一个随机字符串,当需要一个唯一的 ID 时非常方便。
const randomString = () => Math.random().toString(36).slice(2)
console.log( randomString() ) // gi1qtdego0b
console.log( randomString() )// f3qixv40mot
console.log( randomString() )// eeelv1pm3ja
2、获取两个数字之间的随机整数
此方法用于获取两个数字之间的随机整数。
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
console.log( random(1, 50) )// 25
console.log( random(1, 50) )// 34
3、字符串中每个单词的第一个字符大写
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
console.log( uppercaseWords('hello world') ); // 'Hello World'
4、删除数组中的重复值
删除数组的重复项是非常有必要的,使用“Set”会变得非常简单。
const removeDuplicates = (arr) => [...new Set(arr)]
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]))
// [1, 2, 3, 4, 5, 6]
5、删除数组对象的重复值
删除数组对象中重复项
const CSDN = [
{
id: '1',
result: '半'
},
{
id: '1',
result: '半'
},
{
id: '2',
result: '生'
},
{
id: '3',
result: '生'
},
{
id: '3',
result: '过'
},
{
id: '3',
result: '往'
},
{
id: '4',
result: '往'
},
]
let obj = {}
let scdn = CSDN.reduce((cur,next) => {
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
},[]) //设置cur默认类型为数组,并且初始值为空的数组
console.log(scdn );
// 0: {id: '1', result: '半'}
// 1: {id: '2', result: '生'}
// 2: {id: '3', result: '生'}
// 3: {id: '4', result: '往'}
// length: 4
6、展平一个数组
多层数组展开成一层
// 方法一:
const flat = (arr) =>
[].concat.apply(
[],
arr.map((a) => (Array.isArray(a) ? flat(a) : a))
)
// 方法二:
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])
console.log( flat(['半', ['生', '过', ['往']]]) );
// ['半', '生', '过', '往']
7、从数组中删除虚假值
使用此方法,您将能够过滤掉数组中的所有虚假值。
const removeFalsy = (arr) => arr.filter(Boolean)
console.log( removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false]) )
// ['a string', true, 5, 'another string']
8、检查一个数字是偶数还是奇数
可以通过使用模运算符 (%) 来解决。
const isEven = num => num % 2 === 0
console.log( isEven(2) )// true
console.log( isEven(1) )// false
9、获取参数的平均值
我们可以使用 reduce 方法来获取我们在此函数中提供的参数的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
console.log( average(1, 2, 3, 4, 5); ) // 3
10、将数字保留固定小数点
使用 Math.pow() 方法,我们可以将一个数字截断为我们在函数中提供的某个小数点。
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
console.log( round(1.005, 2) ) //1.01
console.log( round(1.555, 2) ) //1.56
console.log( round(1.554, 2) ) //1.55
console.log( round(1.555, 3) ) //1.555
console.log( round(1.555, 1) ) //1.6
11、计算两个日期相差天数
计算两个日期之间的天数,一行代码就可以搞定。
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
console.log( diffDays(new Date("2021-11-3"), new Date("2022-2-1")) )// 100
12、从日期中获取一年中的哪一天
您想知道某个日期是一年中的哪一天吗?
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
console.log( dayOfYear(new Date()) ) // 101
13、生成一个随机的十六进制颜色
如果你需要一个随机的颜色值,这个函数就可以了。
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`
console.log( randomColor() )// #9dae4f
console.log( randomColor() )// #6ef10e
14、将RGB颜色转换为十六进制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
console.log( rgbToHex(255, 255, 255) ) // '#ffffff'
15、清除所有cookies
const clearCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)))
16、检测暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
17、交换两个变量
[a, b] = [b, a]
let a = 1;
let b = 2;
console.log( [a, b] = [b, a] )// a = 2 b = 1
18、暂停一会
const pause = (millis) => new Promise(resolve => setTimeout(resolve, millis))
const fn = async () => {
await pause(1000)
console.log('fatfish') // 1s later
}
fn()