短而精代码段哟
将obj转为url字符串
var queryString = Object.keys(obj).map(key => key + '=' + obj[key]).join('&');
获取URL的查询参数
q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;
//方案二 const getParameters = (URL) => { URL = JSON.parse( '{"' + decodeURI(URL.split("?")[1]) .replace(/"/g, '\\"') .replace(/&/g, '","') .replace(/=/g, '":"') + '"}' ); return JSON.stringify(URL); }; getParameters(window.location); // Result: { search : "easy", page : 3 }
//方案三 Object.fromEntries(new URLSearchParams(window.location.search)) // Result: { search : "easy", page : 3 }
//方案四 const getParamByUrl = (key) => { const url = new URL(location.href) return url.searchParams.get(key) }
展平数组
var arr4=arr3.flat(Infinity)
校验数组是否为空
一行代码检查数组是否为空,将返回true
或false
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0; isNotEmpty([1, 2, 3]); // Result: true
选取对象中的第一个
obj[Object.keys(obj)[0]]
数组对象数据格式根据年龄排序
var arr = [{'name': '张三', age: 26},{'name': '李四', age: 12},{'name': '王五', age: 37},{'name': '赵六', age: 4}];
arr.sort( (a,b)=> b.age-a.age);
console.log(arr)
随机排序
arr.sort( (a,b)=> Math.random()-0.5);
过滤undefined ,NAN,null,false,‘’
arr = arr.filter(val=>!(!val || val== ''));
过滤undefined ,NAN,null,false,‘’的数字数组
arr = arr.map(Number).filter(val=>!(!val || val== ''));
优化if(a==key || b==key || c==key)
[a, b, c].includes(key); // true/false
Set去重
let unique=(a)=>[...new Set(a)];
可对字符串, 数字 null , undefined , NAN , 正则 , 数组 , 函数, 去重
缺点:无法对多重对象去重
var obj = {} var arr2 = array.filter((item, index , array)=>{ return obj.hasOwnProperty(typeof item + item)?false : (obj[typeof item + item]=true) })
再次改良版去重
var obj = {} var arr2 = array.filter((item, index , array)=>{ return obj.hasOwnProperty(JSON.stringify(item) + typeof item + item)?false : (obj[JSON.stringify(item) + typeof item + item]=true) })
过滤id相同项
const result = data.reduce((item, next) => { typeof item.find(ele => ele['id'] === next['id']) === 'undefined' && item.push(next); return item; }, []);
找出数组中重复项
let result = [] arr.forEach(function(item) { if (arr.indexOf(item) !== arr.lastIndexOf(item) && result.indexOf(item) === -1) { result.push(item) } })
非负数代替Math.floor()
~~11.71 //11 11.71 | 0 //11
代替Math.round()
let a=24.7; a-0.5 | 0 // 25
es6解构交换赋值
let [a,b]=[b,a]
使用^判断是否同为正负数
(a^b)>=0 ; //true 相同; false 不相同
快速创建a链接
let b = "我是a标签包裹的文本".link(www.baidu.com)
es6重复字符
let d = "0".repeat(7);//"0000000"
快速判断IE8以下浏览器
let isIE8 = !+"1"
for循环条件简写
for(let i = arr.length;i--){}
隐藏所有指定元素
const hide2 = (el)=>Array.from(el).forEach(e=>(e.style.dispaly="none"))
arguments转化为数组
[].slice.call(arguments, 0) //选其中一种即可 [...arguments] Array.from(arguments)
选择器封装
let $ = name=>document.querySelectorAll(name);
console.log($('div'))
取出两个数组相同之处
let userList = [{id:1},{id:2},{id:3},{id:4},{id:5},{id:6}]; let checkboxList = [{id:1},{id:2}]; let userArr = userList.filter(item =>{return checkboxList.map(item => item.id).includes(item.id)});
数字截断小数位
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed); // Examples toFixed(25.198726354, 1); // 25.1 toFixed(25.198726354, 2); // 25.19
求平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
滚动到页面顶部
const goToTop = () => window.scrollTo(0, 0);
goToTop();
const scrollToTop = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "start" });
滚动到页面底部
const scrollToBottom = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "end" });
判断DOM元素是否获取焦点
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
判断浏览器Tab窗口是否为活动窗口
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
判断奇数偶数
const isEven = num => num % 2 === 0;
判断当前环境是否支持 touch 事件
const touchSupported = () => { ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch); }
判断Apple设备
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
检测设备
const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent ) ? "Mobile" : "Desktop"; console.log(detectDeviceType());
运用三元运算符简写
function test1(){}
function test2(){}
(test3===1?test1:test2)()
在两个数字之间生成一个随机数
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(random(1, 50));
获取浏览器cookie的值
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift(); cookie('_ga');// Result: "GA1.2.1929736587.1601974046"
获取cookie转为对象
const getCookie = () => document.cookie .split(';') .map((item) => item.split('=')) .reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {}) getCookie()
清除全部Cookie
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
颜色rgb转16进制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); rgbToHex(0, 51, 255); // Result: #0033ff
颜色16进制转rgb
const hexToRgb = hex => hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`).substring(1).match(/.{2}/g).map((x) => parseInt(x, 16)); hexToRgb('#00ffff'); // [0, 255, 255] hexToRgb('#0ff'); // [0, 255, 255]
复制到剪切板
借助navigator.clipboard.writeText
可以很容易的讲文本复制到剪贴板
规范要求在写入剪贴板之前使用 Permissions API 获取“剪贴板写入”权限。
但是,不同浏览器的具体要求不同,因为这是一个新的API
onst copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
检查日期是否合法
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf()); isDateValid("December 17, 1995 03:24:00");// Result: true
查找日期位于一年中的第几天
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); dayOfYear(new Date());// Result: 272
英文字符串首字母大写
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1) capitalize("follow for more")// Result: Follow for more
计算2个日期之间相差多少天
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000) dayDif(new Date("2020-10-21"), new Date("2021-10-22"))// Result: 366
生成随机十六进制颜色
可以使用 Math.random
和 padEnd
属性生成随机的十六进制颜色。
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`; console.log(randomHex());// Result: #92b008
const getRandomColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}`
getRandomColor() // '#4c2fd7'
获取用户选择的文本
使用内置的getSelection
属性获取用户选择的文本。
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
检查用户的设备是否处于暗模式
使用以下代码检查用户的设备是否处于暗模式。
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches console.log(isDarkMode) // Result: True or False
检查对象是否为空
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
检查设备上的触摸支持
const touchSupported = () => ('ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch)
在元素后插入一串 HTML
const insertHTMLAfter = (html, el) => el.insertAdjacentHTML('afterend', html)
在网页上获取选定的文本
const getSelectedText = () => window.getSelection().toString()
一行代码实现星级评分
const getRate = (rate = 0) => '★★★★★☆☆☆☆☆'.slice(5 - rate, 10 - rate);
getRate(3);
构造函数判断数据类型
let obj = {}
obj.constructor.name
创建唯一id
createdUuid() { function S4() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) } return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4() }
const uuid = (a) => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid))
简化if判断函数执行
(test3 === 1? test1:test2)();
生成随机颜色
const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}`
console.log(generateRandomHexColor())
强制等待
当你需要等待一段时间,但又不想写在setTimeout函数中,造成回调地狱
const sleep = async (t) => new Promise((resolve) => setTimeout(resolve, t)); sleep(2000).then(() => {console.log('time')});
比较两个对象
const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0])) isEqual({name: 'jack'}, {name: 'jack'}) // true isEqual({name: 'jack'}, {name: 'jack1'}, {name: 'jack'}) // false
多数组取交集
const intersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)))
intersection([1, 2, 3, 4], [2, 3, 4, 7, 8], [1, 3, 4, 9])
// [3, 4]
intersection([1, 2, 3, 4], [2, 3, 4, 7, 8], [1, 3, 4, 9])
// [3, 4]
压缩多个数组
多个数组压缩成一个数组
const zip = (...arr) => Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_, i) => arr.map((a) => a[i])) zip([1,2,3,4], ['a', 'b', 'c', 'd'], ['A', 'B', 'C', 'D']) // [[1, 'a', 'A'], [2, 'b', 'B'], [3, 'c', 'C'], [4, 'd', 'D']]
矩阵交换行和列
const transpose = (matrix) => matrix[0].map((col, i) => matrix.map((row) => row[i])); transpose( [ // [ [1, 2, 3], // [1, 4, 7], [4, 5, 6], // [2, 5, 8], [7, 8, 9], // [3, 6, 9], ] // ] );
从给定文本中剥离html
const stripHtml = (html) => new DOMParser().parseFromString(html, 'text/html').body.textContent || ''; stripHtml('<div>test</div>') // 'test'
秒数转换
const formatSeconds = (s) => new Date(s * 1000).toISOString().substr(11, 8) formatSeconds(200) // 00:03:20
截断数字
小数点后的某些数字截断而不取四舍五入
const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\d+(?:.\d{0,${fixed}})?`))[0] toFixed(10.255, 2) // 10.25
补零
const replenishZero = (num, len, zero = 0) => num.toString().padStart(len, zero) replenishZero(8, 2) // 08
反转对象键值
const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {}) invert({name: 'jack'}) // {jack: 'name'}
字符串转对象
当你需要将一串字符串比如'{name: "jack"}'转换成对象时,直接使用JSON.parse将会报错。
const strParse = (str) => JSON.parse(str.replace(/(\w+)\s*:/g, (_, p1) => `"${p1}":`).replace(/\'/g, "\""))
strParse('{name: "jack"}')
去除多余空格
const setTrimOut = str => str.replace(/\s\s+/g, ' ') const str = setTrimOut('hello, jack') //
..