短而精代码段哟
将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 }
展平数组
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();
判断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);
运用三元运算符简写
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"
颜色rgb转16进制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); rgbToHex(0, 51, 255); // Result: #0033ff
复制到剪切板
借助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
清除全部Cookie
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
生成随机十六进制颜色
可以使用 Math.random 和 padEnd 属性生成随机的十六进制颜色。
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex());// Result: #92b008
获取用户选择的文本
使用内置的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
..