javascript 工作中罕用单行代码汇总
替换两个变量
[foo, bar] = [bar, foo]
生成随机字符串
const randomString = () => Math.random().toString(36).slice(2)
randomString() // g21qtdego0s
本义 HTML 特殊字符
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
uppercaseWords('hello world'); // 'Hello World'
判断邮箱
export const isEmail = (s) => {return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}
手机号码
export const isMobile = (s) => {return /^1[0-9]{10}$/.test(s)
}
是否为 null
export const isNull = (o) => {return Object.prototype.toString.call(o).slice(8, -1) === 'Null'
}
是否 undefined
export const isUndefined = (o) => {return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined'
}
是否是数组
export const isArray = (o) => {return Object.prototype.toString.call(o).slice(8, -1) === 'Array'
}
是否是挪动端
export const isDeviceMobile = () => {return /android|webos|iphone|ipod|balckberry/i.test(ua)
}
去除 html 标签
export const removeHtmltag = (str) => {return str.replace(/<[^>]+>/g, '')
}
获取 url 参数
export const getQueryString = (name) => {const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
const search = window.location.search.split('?')[1] || '';
const r = search.match(reg) || [];
return r[2];
}
删除数组中的反复值
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]
展平一个数组
const flat = (arr) =>
[].concat.apply([],
arr.map((a) => (Array.isArray(a) ? flat(a) : a))
)
// Or
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])
flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']
从数组中删除虚伪值
const removeFalsy = (arr) => arr.filter(Boolean)
removeFalsy([0, 'a string', '', NaN, true, 5, undefined,'another string', false])
// ['a string', true, 5, 'another string']
获取两个数之间的随机整数
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
random(1, 50) // 25
random(1, 50) // 34
计算两个日期相差天数
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date("2022-1-3"), new Date("2022-2-1")) // 90
从日期中获取一年中的哪一天
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
dayOfYear(new Date())
革除所有 cookies
const clearCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)))
生成随机色彩
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`
randomColor() // #9dae4f
randomColor() // #6ef10e