JS中可能会常用到的一些数据处理方法
DOM处理
DOM 为文档提供了结构化表示,并定义了如何通过脚本来访问文档结构。目的其实就是为了能让js操作html元素而制定的一个规范。DOM就是由节点组成的。
检查一个元素是否被聚焦
const hasFocus = ele => (ele === document.activeElement);
检查用户是否滚动到页面底部
const isAtBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
获取一个元素的所有兄弟元素
const siblings = ele => [].slice.call(ele.parentNode.children).filter((child) => (child !== ele));
获取元素相对于文档的位置
const getPosition = ele => (r = ele.getBoundingClientRect(), { left: r.left + window.scrollX, top: r.top + window.scrollY }); // Example getPosition(document.body); // { left: 0, top: 0 }
在另一个元素之后插入一个元素
const insertAfter = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling); // Or const insertAfter = (ele, anotherEle) => anotherEle.insertAdjacentElement('afterend', ele);
附:在其他元素之前插入一个元素
const insertBefore = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle); // Or const insertBefore = (ele, anotherEle) => anotherEle.insertAdjacentElement('beforebegin', ele);
在元素后面插入给定的 HTML
const insertHtmlAfter = (html, ele) => ele.insertAdjacentHTML('afterend', html);
附:在元素之前插入给定的 HTML
const insertHtmlBefore = (html, ele) => ele.insertAdjacentHTML('beforebegin', html);
滚动到页面顶部(返回顶部)
const goToTop = () => window.scrollTo(0, 0);
数组
数组判空
// `arr` is an array const isEmpty = arr => !Array.isArray(arr) || arr.length === 0; // Examples isEmpty([]); // true isEmpty([1, 2, 3]); // false
克隆数组
// `arr` is an array const clone = arr => arr.slice(0); // Or const clone = arr => [...arr]; // Or const clone = arr => Array.from(arr); // Or const clone = arr => arr.map(x => x); // Or const clone = arr => JSON.parse(JSON.stringify(arr)); // Or const clone = arr => arr.concat([]);
找到数组中最大值对应的索引
const indexOfMax = arr => arr.reduce((prev, curr, i, a) => curr > a[prev] ? i : prev, 0); // Examples indexOfMax([1, 3, 9, 7, 5]); // 2 indexOfMax([1, 3, 7, 7, 5]); // 2
附:最小值对应的索引
const indexOfMin = arr => arr.reduce((prev, curr, i, a) => curr < a[prev] ? i : prev, 0); // Examples indexOfMin([6, 4, 8, 2, 10]); // 3 indexOfMin([6, 4, 2, 2, 10]); // 2
获取数组的交集
const getIntersection = (a, ...arr) => [...new Set(a)].filter(v => arr.every(b => b.includes(v))); // Examples getIntersection([1, 2, 3], [2, 3, 4, 5]); // [2, 3] getIntersection([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]); // [3]
按键对一组对象进行分组
const groupBy = (arr, key) => arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {}); // Example groupBy([ { branch: 'audi', model: 'q8', year: '2019' }, { branch: 'audi', model: 'rs7', year: '2020' }, { branch: 'ford', model: 'mustang', year: '2019' }, { branch: 'ford', model: 'explorer', year: '2020' }, { branch: 'bmw', model: 'x7', year: '2020' }, ], 'branch'); /* { audi: [ { branch: 'audi', model: 'q8', year: '2019' }, { branch: 'audi', model: 'rs7', year: '2020' } ], bmw: [ { branch: 'bmw', model: 'x7', year: '2020' } ], ford: [ { branch: 'ford', model: 'mustang', year: '2019' }, { branch: 'ford', model: 'explorer', year: '2020' } ], } */
删除数组中的重复值
const removeDuplicate = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); // Example removeDuplicate(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']); // ['h', 'e', 'w', 'r', 'd']
按给定的键对数组中的项进行排序
const sortBy = (arr, k) => arr.concat().sort((a, b) => (a[k] > b[k]) ? 1 : ((a[k] < b[k]) ? -1 : 0)); // Example const people = [ { name: 'Foo', age: 42 }, { name: 'Bar', age: 24 }, { name: 'Fuzz', age: 36 }, { name: 'Baz', age: 32 }, ]; sortBy(people, 'age'); // returns // [ // { name: 'Bar', age: 24 }, // { name: 'Baz', age: 32 }, // { name: 'Fuzz', age: 36 }, // { name: 'Foo', age: 42 }, // ]
方法
将 URL 参数转换为对象
const getUrlParams = query => Array.from(new URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v}), {}); // Examples getUrlParams(location.search); // Get the parameters of the current URL getUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" } // Duplicate key getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }
从 URL 获取参数的值
const getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param); // Example getParam('http://domain.com?message=hello', 'message'); // 'hello'
用零作为整数的前缀
const prefixWithZeros = (number, length) => (number / Math.pow(10, length)).toFixed(length).substr(2); // Or const prefixWithZeros = (number, length) => `${Array(length).join('0')}${number}`.slice(-length); // Or const prefixWithZeros = (number, length) => String(number).padStart(length, '0'); // Example prefixWithZeros(42, 5); // '00042'
将数字四舍五入到给定的数字位数
const prefixWithZeros = (number, length) => (number / Math.pow(10, length)).toFixed(length).substr(2); // Or const prefixWithZeros = (number, length) => `${Array(length).join('0')}${number}`.slice(-length); // Or const prefixWithZeros = (number, length) => String(number).padStart(length, '0'); // Example prefixWithZeros(42, 5); // '00042'
将一个数字截断为给定的小数位数而不进行舍入
const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\\d+(?:\.\\d{0,${fixed}})?`))[0]; // Or 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 toFixed(25.198726354, 3); // 25.198 toFixed(25.198726354, 4); // 25.1987 toFixed(25.198726354, 5); // 25.19872 toFixed(25.198726354, 6); // 25.198726
从对象中移除所有 null 和未定义的属性
const removeNullUndefined = obj => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : (a[k] = v, a)), {}); // Or const removeNullUndefined = obj => Object.entries(obj).filter(([_, v]) => v != null).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}); // Or const removeNullUndefined = obj => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null)); // Example removeNullUndefined({ foo: null, bar: undefined, fuzz: 42, });
检查字符串是否为回文
const isPalindrome = str => str === str.split('').reverse().join(''); // Examples isPalindrome('abc'); // false isPalindrom('abcba'); // true
将一个字符串转换为 camelCase
const toCamelCase = str => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : ''); // Examples toCamelCase('background-color'); // backgroundColor toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb toCamelCase('_hello_world'); // HelloWorld toCamelCase('hello_world'); // helloWorld
将字符串转换为 PascalCase
const toPascalCase = str => (str.match(/[a-zA-Z0-9]+/g) || []).map(w => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join(''); // Examples toPascalCase('hello world'); // 'HelloWorld' toPascalCase('hello.world'); // 'HelloWorld' toPascalCase('foo_bar-baz'); // FooBarBaz
转义 HTML 特殊字符
const escape = str => str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, ''').replace(/"/g, '"'); // Or const escape = str => str.replace(/[&<>"']/g, m => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[m]);
将多个空格替换为单个空格
// Replace spaces, tabs and new line characters const replaceSpaces = str => str.replace(/\s\s+/g, ' '); // Only replace spaces const replaceOnlySpaces = str => str.replace(/ +/g, ' '); // Example replaceSpaces('this\n is \ta \rmessage'); // 'this is a message'
在字母顺序中对文本文档的行进行排序
const sortLines = str => str.split(/\r?\n/).sort().join('\n'); // Reverse the order const reverseSortedLines = str => str.split(/\r?\n/).sort().reverse().join('\n'); // Example sortLines(`Thaddeus Mullen Kareem Marshall Ferdinand Valentine Hasad Lindsay Mufutau Berg Knox Tyson Kasimir Fletcher Colton Sharp Adrian Rosales Theodore Rogers`); /* Output */ /* Adrian Rosales Colton Sharp Ferdinand Valentine Hasad Lindsay Kareem Marshall Kasimir Fletcher Knox Tyson Mufutau Berg Thaddeus Mullen Theodore Rogers */
将字符串截断为完整的单词(超出隐藏)
const truncate = (str, max, suffix) => str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`; // Example truncate('This is a long message', 20, '...'); // 'This is a long...'
取消转义 HTML 特殊字符
const unescape = str => str.replace(/&/g , '&').replace(/</g , '<').replace(/>/g , '>').replace(/�*39;/g , "'").replace(/"/g, '"');
总结
到此这篇关于JS中可能会常用到的一些数据处理方法的文章就介绍到这了,更多相关JS常用数据处理方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
最新评论