整理js单行技巧
数组去重 es6 new Set()
const uniqueArr = (arr) => [...new Set(arr)];
console.log(uniqueArr(["前端","js","html","js","css","html"]));
// ['前端', 'js', 'html', 'css']
从url获取参数并转为对象
网页路径经常是:www.baidu.com?search=js&xxx=kkk这种形式的,我们是经常需要取参数的,可以使用第三方的qs包实现,如果你只是要实现取参数,这一句代码就可以实现,不用再引入qs了。
const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`
)
getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1");
// {q: 'js+md', newwindow: '1'}
检查对象是否为空
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
isEmpty({}) // true
isEmpty({a:"not empty"}) //false
检查对象是否为空,实际上并不那么简单,即使对象为空,每次检查对象是否等于 {} 也会返回 false。
反转字符串
反转字符串可以使用split结合reverse和join方法轻松实现。
const reverse = str => str.split('').reverse().join('');
reverse('this is reverse');
// esrever si siht
检测元素是否处于焦点
activeElement 属性返回文档中当前获得焦点的元素。
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// 元素处于焦点返回true,反之返回false