您当前的位置:首页 > 网站建设 > javascript
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax |

JS中可能会常用到的一些数据处理方法

51自学网 2022-05-02 21:31:08
  javascript

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 });// ExamplegetPosition(document.body);     // { left: 0, top: 0 }

在另一个元素之后插入一个元素

const insertAfter = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling);// Orconst insertAfter = (ele, anotherEle) => anotherEle.insertAdjacentElement('afterend', ele);

附:在其他元素之前插入一个元素

const insertBefore = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle);// Orconst 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 arrayconst isEmpty = arr => !Array.isArray(arr) || arr.length === 0;// ExamplesisEmpty([]);            // trueisEmpty([1, 2, 3]);     // false

克隆数组

// `arr` is an arrayconst clone = arr => arr.slice(0);// Orconst clone = arr => [...arr];// Orconst clone = arr => Array.from(arr);// Orconst clone = arr => arr.map(x => x);// Orconst clone = arr => JSON.parse(JSON.stringify(arr));// Orconst clone = arr => arr.concat([]);

找到数组中最大值对应的索引

const indexOfMax = arr => arr.reduce((prev, curr, i, a) => curr > a[prev] ? i : prev, 0);// ExamplesindexOfMax([1, 3, 9, 7, 5]);        // 2indexOfMax([1, 3, 7, 7, 5]);        // 2

附:最小值对应的索引

const indexOfMin = arr => arr.reduce((prev, curr, i, a) => curr < a[prev] ? i : prev, 0);// ExamplesindexOfMin([6, 4, 8, 2, 10]);       // 3indexOfMin([6, 4, 2, 2, 10]);       // 2

获取数组的交集

const getIntersection = (a, ...arr) => [...new Set(a)].filter(v => arr.every(b => b.includes(v)));// ExamplesgetIntersection([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), {});// ExamplegroupBy([    { 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));// ExampleremoveDuplicate(['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));// Exampleconst 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}), {});// ExamplesgetUrlParams(location.search);              // Get the parameters of the current URLgetUrlParams('foo=Foo&bar=Bar');            // { foo: "Foo", bar: "Bar" }// Duplicate keygetUrlParams('foo=Foo&foo=Fuzz&bar=Bar');   // { foo: ["Foo", "Fuzz"], bar: "Bar" }

从 URL 获取参数的值

const getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param);// ExamplegetParam('http://domain.com?message=hello', 'message');     // 'hello'

用零作为整数的前缀

const prefixWithZeros = (number, length) => (number / Math.pow(10, length)).toFixed(length).substr(2);// Orconst prefixWithZeros = (number, length) => `${Array(length).join('0')}${number}`.slice(-length);// Orconst prefixWithZeros = (number, length) => String(number).padStart(length, '0');// ExampleprefixWithZeros(42, 5);     // '00042'

将数字四舍五入到给定的数字位数

const prefixWithZeros = (number, length) => (number / Math.pow(10, length)).toFixed(length).substr(2);// Orconst prefixWithZeros = (number, length) => `${Array(length).join('0')}${number}`.slice(-length);// Orconst prefixWithZeros = (number, length) => String(number).padStart(length, '0');// ExampleprefixWithZeros(42, 5);     // '00042'

将一个数字截断为给定的小数位数而不进行舍入

const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?//d+(?:/.//d{0,${fixed}})?`))[0];// Orconst toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);// ExamplestoFixed(25.198726354, 1);       // 25.1toFixed(25.198726354, 2);       // 25.19toFixed(25.198726354, 3);       // 25.198toFixed(25.198726354, 4);       // 25.1987toFixed(25.198726354, 5);       // 25.19872toFixed(25.198726354, 6);       // 25.198726

从对象中移除所有 null 和未定义的属性

const removeNullUndefined = obj => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : (a[k] = v, a)), {});// Orconst removeNullUndefined = obj => Object.entries(obj).filter(([_, v]) => v != null).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});// Orconst removeNullUndefined = obj => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));// ExampleremoveNullUndefined({    foo: null,    bar: undefined,    fuzz: 42,});  

检查字符串是否为回文

const isPalindrome = str => str === str.split('').reverse().join('');// ExamplesisPalindrome('abc');        // falseisPalindrom('abcba');       // true

将一个字符串转换为 camelCase

const toCamelCase = str => str.trim().replace(/[-_/s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');// ExamplestoCamelCase('background-color');            // backgroundColortoCamelCase('-webkit-scrollbar-thumb');     // WebkitScrollbarThumbtoCamelCase('_hello_world');                // HelloWorldtoCamelCase('hello_world');                 // helloWorld

将字符串转换为 PascalCase

const toPascalCase = str => (str.match(/[a-zA-Z0-9]+/g) || []).map(w => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join('');// ExamplestoPascalCase('hello world');    // 'HelloWorld'toPascalCase('hello.world');    // 'HelloWorld'toPascalCase('foo_bar-baz');    // FooBarBaz

转义 HTML 特殊字符

const escape = str => str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;');// Orconst escape = str => str.replace(/[&<>"']/g, m => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[m]);

将多个空格替换为单个空格

// Replace spaces, tabs and new line charactersconst replaceSpaces = str => str.replace(//s/s+/g, ' ');// Only replace spacesconst replaceOnlySpaces = str => str.replace(/  +/g, ' ');// ExamplereplaceSpaces('this/n   is     /ta    /rmessage');  // 'this is a message'

在字母顺序中对文本文档的行进行排序

const sortLines = str => str.split(//r?/n/).sort().join('/n');// Reverse the orderconst reverseSortedLines = str => str.split(//r?/n/).sort().reverse().join('/n');// ExamplesortLines(`Thaddeus MullenKareem MarshallFerdinand ValentineHasad LindsayMufutau BergKnox TysonKasimir FletcherColton SharpAdrian RosalesTheodore Rogers`);/* Output *//*Adrian RosalesColton SharpFerdinand ValentineHasad LindsayKareem MarshallKasimir FletcherKnox TysonMufutau BergThaddeus MullenTheodore Rogers*/

将字符串截断为完整的单词(超出隐藏)

const truncate = (str, max, suffix) => str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`;// Exampletruncate('This is a long message', 20, '...');  // 'This is a long...'

取消转义 HTML 特殊字符

const unescape = str => str.replace(/&amp;/g , '&').replace(/&lt;/g  , '<').replace(/&gt;/g  , '>').replace(/�*39;/g , "'").replace(/&quot;/g, '"');

总结

到此这篇关于JS中可能会常用到的一些数据处理方法的文章就介绍到这了,更多相关JS常用数据处理方法内容请搜索wanshiok.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持wanshiok.com!


Vue实现动态圆环百分比进度条
vue实现动态进度条效果
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1