JS中可能會(huì)常用到的一些數(shù)據(jù)處理方法
DOM處理
DOM 為文檔提供了結(jié)構(gòu)化表示,并定義了如何通過(guò)腳本來(lái)訪問(wèn)文檔結(jié)構(gòu)。目的其實(shí)就是為了能讓js操作html元素而制定的一個(gè)規(guī)范。DOM就是由節(jié)點(diǎn)組成的。
檢查一個(gè)元素是否被聚焦
const hasFocus = ele => (ele === document.activeElement);
檢查用戶是否滾動(dòng)到頁(yè)面底部
const isAtBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
獲取一個(gè)元素的所有兄弟元素
const siblings = ele => [].slice.call(ele.parentNode.children).filter((child) => (child !== ele));
獲取元素相對(duì)于文檔的位置
const getPosition = ele => (r = ele.getBoundingClientRect(), { left: r.left + window.scrollX, top: r.top + window.scrollY }); // Example getPosition(document.body); // { left: 0, top: 0 }
在另一個(gè)元素之后插入一個(gè)元素
const insertAfter = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling); // Or const insertAfter = (ele, anotherEle) => anotherEle.insertAdjacentElement('afterend', ele);
附:在其他元素之前插入一個(gè)元素
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);
滾動(dòng)到頁(yè)面頂部(返回頂部)
const goToTop = () => window.scrollTo(0, 0);
數(shù)組
數(shù)組判空
// `arr` is an array const isEmpty = arr => !Array.isArray(arr) || arr.length === 0; // Examples isEmpty([]); // true isEmpty([1, 2, 3]); // false
克隆數(shù)組
// `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([]);
找到數(shù)組中最大值對(duì)應(yīng)的索引
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
附:最小值對(duì)應(yīng)的索引
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
獲取數(shù)組的交集
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]
按鍵對(duì)一組對(duì)象進(jìn)行分組
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' } ], } */
刪除數(shù)組中的重復(fù)值
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']
按給定的鍵對(duì)數(shù)組中的項(xiàng)進(jìn)行排序
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 參數(shù)轉(zhuǎn)換為對(duì)象
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 獲取參數(shù)的值
const getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param); // Example getParam('http://domain.com?message=hello', 'message'); // 'hello'
用零作為整數(shù)的前綴
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'
將數(shù)字四舍五入到給定的數(shù)字位數(shù)
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'
將一個(gè)數(shù)字截?cái)酁榻o定的小數(shù)位數(shù)而不進(jìn)行舍入
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
從對(duì)象中移除所有 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
將一個(gè)字符串轉(zhuǎn)換為 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
將字符串轉(zhuǎn)換為 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
轉(zhuǎn)義 HTML 特殊字符
const escape = str => str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, ''').replace(/"/g, '"'); // Or const escape = str => str.replace(/[&<>"']/g, m => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[m]);
將多個(gè)空格替換為單個(gè)空格
// 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'
在字母順序中對(duì)文本文檔的行進(jìn)行排序
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 */
將字符串截?cái)酁橥暾膯卧~(超出隱藏)
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...'
取消轉(zhuǎn)義 HTML 特殊字符
const unescape = str => str.replace(/&/g , '&').replace(/</g , '<').replace(/>/g , '>').replace(/�*39;/g , "'").replace(/"/g, '"');
總結(jié)
到此這篇關(guān)于JS中可能會(huì)常用到的一些數(shù)據(jù)處理方法的文章就介紹到這了,更多相關(guān)JS常用數(shù)據(jù)處理方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
js 靜態(tài)動(dòng)態(tài)成員 and 信息的封裝和隱藏
一下用面向?qū)ο蟮南嚓P(guān)概念來(lái)解釋js中的仿面向?qū)ο螅驗(yàn)閖s中不像其他語(yǔ)言,不存在面向?qū)ο笳Z(yǔ)言的相關(guān)特性2011-05-05基于javascript實(shí)現(xiàn)貪吃蛇小游戲
這篇文章主要介紹了基于javascript實(shí)現(xiàn)貪吃蛇小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11JS實(shí)現(xiàn)超精簡(jiǎn)的鏈接列表在固定區(qū)域內(nèi)滾動(dòng)效果代碼
這篇文章主要介紹了JS實(shí)現(xiàn)超精簡(jiǎn)的鏈接列表在固定區(qū)域內(nèi)滾動(dòng)效果代碼,非常常見(jiàn)的頁(yè)面元素屬性變換控制實(shí)現(xiàn)滾動(dòng)效果,簡(jiǎn)單實(shí)用,需要的朋友可以參考下2015-11-11js實(shí)現(xiàn)的Easy Tabs選項(xiàng)卡用法實(shí)例
這篇文章主要介紹了js實(shí)現(xiàn)的Easy Tabs選項(xiàng)卡用法,以完整實(shí)例形式較為詳細(xì)的分析了JavaScript鼠標(biāo)事件動(dòng)態(tài)操作頁(yè)面元素樣式的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-09-09js或css實(shí)現(xiàn)滾動(dòng)廣告的幾種方案
今天無(wú)事逛網(wǎng),突然發(fā)現(xiàn)了一個(gè)很有趣的事情,(也許只有我覺(jué)得有趣).我看到一圖片竟然在我拖動(dòng)滾動(dòng)條的時(shí)候沒(méi)有動(dòng),也許你會(huì)說(shuō)我少見(jiàn)多怪,不信你去找個(gè)這樣的我看看,很少有的,一般的都是一拖動(dòng)圖片就在那跳得厲害。2010-01-01csdn 博客中實(shí)現(xiàn)運(yùn)行代碼功能實(shí)現(xiàn)
有時(shí)候因?yàn)閏sdn的博客經(jīng)常處理一些字符,導(dǎo)致代碼很多情況下,都不能正常運(yùn)行,給大家的閱讀帶來(lái)了麻煩,下面是腳本之家編輯簡(jiǎn)單的整理下。2009-08-08JavaScript運(yùn)行機(jī)制實(shí)例分析
這篇文章主要介紹了JavaScript運(yùn)行機(jī)制,結(jié)合實(shí)例形式分析JavaScript運(yùn)行機(jī)制相關(guān)原理、使用方法及操作注意事項(xiàng),需要的朋友可以參考下2020-04-04