开发中常用的25个JavaScript单行代码(小结)(2)

const objectToQueryString = (obj) => Object.keys(obj).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`).join('&'); objectToQueryString({name: 'Jhon', age: 18, address: 'beijing'}) // name=Jhon&age=18&address=beijing

13.获取数组交集

const similarity = (arr, values) => arr.filter(v => values.includes(v)); similarity([1, 2, 3], [1, 2, 4]); // [1,2]

14.检测设备类型

使用正则表达式来检测 navigator.userAgent 属性判断设备是在移动设备还是在台式机/笔记本电脑打开。

const detectDeviceType = () =>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';

15. 将数字转化为千分位格式

const toDecimalMark = num => num.toLocaleString('en-US'); toDecimalMark(12305030388.9087); // "12,305,030,388.909"

16 多维数组转一维数组

const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]

17.过滤对象数组

const reducedFilter = (data, keys, fn) =>data.filter(fn).map(el =>keys.reduce((acc, key) => {acc[key] =el[key];return acc;}, {})); const data = [ { id: 1, name: 'john', age: 24 }, { id: 2, name: 'mike', age: 50 } ]; let a = reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]

18.驼峰字字符串格式化

转换驼峰拼写的字符串为特定格式。

使用 String.replace() 去除下划线,连字符和空格,并将驼峰拼写格式的单词转换为全小写。省略第二个参数 separator ,默认使用 _ 分隔符。

const fromCamelCase = (str, separator = '_') =>str.replace(/([a-zd])([A-Z])/g, '$1' + separator + '$2').replace(/([A-Z]+)([A-Z][a-zd]+)/g, '$1' + separator + '$2').toLowerCase(); fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name' fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized' fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'

19.是否为绝对地址

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); isAbsoluteURL('https://google.com'); // true isAbsoluteURL('ftp://www.myserver.net'); // true isAbsoluteURL('/foo/bar'); // false

20.获取两个日期相差天数

const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9

21.数组去重

const deDupe = (myArray) => [... new Set(myArray)]; deDupe([1, 1, 2, 1, 3, 3, 4]) // [1, 2, 3, 4]

22.数组对象去重

const uniqueElementsBy = (arr, fn) =>arr.reduce((acc, v) => {if (!acc.some(x => fn(v, x))) acc.push(v);return acc;}, []); uniqueElementsBy([{id: 1, name: 'Jhon'}, {id: 2, name: 'sss'}, {id: 1, name: 'Jhon'}], (a, b) => a.id == b.id) // [{id: 1, name: 'Jhon'}, {id: 2, name: 'sss'}]

23. RGB 颜色转 16进制颜色

const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); RGBToHex(255, 165, 1); // 'ffa501'

24. 常用密码组合正则

const passwordReg = /(?!^(d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[w~!@#$%^&*?]{8,20}$/; // -长度8~20位字符,支持大小写字母、数字、符号三种字符中任意两种字符的组合

25. 判断dom元素是否具有某个className

const hasClass = (el, className) => new RegExp(`(^|\s)${className}(\s|$)`).test(el.className);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/7ddb61014be51dfa8b20bcdc226b2922.html