自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

記好這 24 個 ES6 方法,用來解決實際開發(fā)的 JS 問題

開發(fā) 前端
本文主要介紹 24 中 es6 方法,這些方法都挺實用的,本本請記好,時不時翻出來看看。

[[355115]]

本文已經(jīng)原作者 Madza 授權(quán)翻譯。

本文主要介紹 24 中 es6 方法,這些方法都挺實用的,本本請記好,時不時翻出來看看。

1.如何隱藏所有指定的元素

  1. const hide = (...el) => [...el].forEach(e => (e.style.display = 'none')) 
  2.  
  3. // 事例:隱藏頁面上所有`<img>`元素? 
  4. hide(document.querySelectorAll('img')) 

2.如何檢查元素是否具有指定的類?

頁面DOM里的每個節(jié)點上都有一個classList對象,程序員可以使用里面的方法新增、刪除、修改節(jié)點上的CSS類。使用classList,程序員還可以用它來判斷某個節(jié)點是否被賦予了某個CSS類。

  1. const hasClass = (el, className) => el.classList.contains(className) 
  2.  
  3. // 事例 
  4. hasClass(document.querySelector('p.special'), 'special') // true 

3.如何切換一個元素的類?

  1. const toggleClass = (el, className) => el.classList.toggle(className) 
  2.  
  3. // 事例 移除 p 具有類`special`的 special 類 
  4. toggleClass(document.querySelector('p.special'), 'special'

4.如何獲取當(dāng)前頁面的滾動位置?

  1. const getScrollPosition = (el = window) => ({ 
  2.   x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, 
  3.   y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop 
  4. }); 
  5.  
  6. // 事例 
  7. getScrollPosition(); // {x: 0, y: 200} 

5.如何平滑滾動到頁面頂部

  1. const scrollToTop = () => { 
  2.   const c = document.documentElement.scrollTop || document.body.scrollTop; 
  3.   if (c > 0) { 
  4.     window.requestAnimationFrame(scrollToTop); 
  5.     window.scrollTo(0, c - c / 8); 
  6.   } 
  7.  
  8. // 事例 
  9. scrollToTop() 

window.requestAnimationFrame() 告訴瀏覽器——你希望執(zhí)行一個動畫,并且要求瀏覽器在下次重繪之前調(diào)用指定的回調(diào)函數(shù)更新動畫。該方法需要傳入一個回調(diào)函數(shù)作為參數(shù),該回調(diào)函數(shù)會在瀏覽器下一次重繪之前執(zhí)行。

requestAnimationFrame:優(yōu)勢:由系統(tǒng)決定回調(diào)函數(shù)的執(zhí)行時機。60Hz的刷新頻率,那么每次刷新的間隔中會執(zhí)行一次回調(diào)函數(shù),不會引起丟幀,不會卡頓。

6.如何檢查父元素是否包含子元素?

  1. const elementContains = (parent, child) => parent !== child && parent.contains(child); 
  2.  
  3. // 事例 
  4. elementContains(document.querySelector('head'), document.querySelector('title'));  
  5. // true 
  6. elementContains(document.querySelector('body'), document.querySelector('body'));  
  7. // false 

7.如何檢查指定的元素在視口中是否可見?

  1. const elementIsVisibleInViewport = (el, partiallyVisible = false) => { 
  2.   const { topleft, bottom, right } = el.getBoundingClientRect(); 
  3.   const { innerHeight, innerWidth } = window; 
  4.   return partiallyVisible 
  5.     ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && 
  6.         ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) 
  7.     : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; 
  8. }; 
  9.  
  10. // 事例 
  11. elementIsVisibleInViewport(el); // 需要左右可見 
  12. elementIsVisibleInViewport(el, true); // 需要全屏(上下左右)可以見 

8.如何獲取元素中的所有圖像?

  1. const getImages = (el, includeDuplicates = false) => { 
  2.   const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src')); 
  3.   return includeDuplicates ? images : [...new Set(images)]; 
  4. }; 
  5.  
  6. // 事例:includeDuplicates 為 true 表示需要排除重復(fù)元素 
  7. getImages(document, true); // ['image1.jpg''image2.png''image1.png''...'
  8. getImages(document, false); // ['image1.jpg''image2.png''...'

9.如何確定設(shè)備是移動設(shè)備還是臺式機/筆記本電腦?

  1. const detectDeviceType = () => 
  2.   /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) 
  3.     ? 'Mobile' 
  4.     : 'Desktop'
  5.  
  6. // 事例 
  7. detectDeviceType(); // "Mobile" or "Desktop" 

10.How to get the current URL?

  1. const currentURL = () => window.location.href 
  2.  
  3. // 事例 
  4. currentURL() // 'https://google.com' 

11.如何創(chuàng)建一個包含當(dāng)前URL參數(shù)的對象?

  1. const getURLParameters = url => 
  2.   (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( 
  3.     (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), 
  4.     {} 
  5.   ); 
  6.  
  7. // 事例 
  8. getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'
  9. getURLParameters('google.com'); // {} 

12.如何將一組表單元素轉(zhuǎn)化為對象?

  1. const formToObject = form => 
  2.   Array.from(new FormData(form)).reduce( 
  3.     (acc, [key, value]) => ({ 
  4.       ...acc, 
  5.       [key]: value 
  6.     }), 
  7.     {} 
  8.   ); 
  9.  
  10. // 事例 
  11. formToObject(document.querySelector('#form'));  
  12. // { email: 'test@email.com'name'Test Name' } 

13.如何從對象檢索給定選擇器指示的一組屬性?

  1. const get = (from, ...selectors) => 
  2.   [...selectors].map(s => 
  3.     s 
  4.       .replace(/\[([^\[\]]*)\]/g, '.$1.'
  5.       .split('.'
  6.       .filter(t => t !== ''
  7.       .reduce((prev, cur) => prev && prev[cur], from
  8.   ); 
  9. const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] }; 
  10.  
  11. // Example 
  12. get(obj, 'selector.to.val''target[0]''target[2].a');  
  13. // ['val to select', 1, 'test'

14.如何在等待指定時間后調(diào)用提供的函數(shù)?

  1. const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); 
  2. delay( 
  3.   function(text) { 
  4.     console.log(text); 
  5.   }, 
  6.   1000, 
  7.   'later' 
  8. );  
  9.  
  10. // 1秒后打印 'later' 

15.如何在給定元素上觸發(fā)特定事件且能選擇地傳遞自定義數(shù)據(jù)?

  1. const triggerEvent = (el, eventType, detail) => 
  2.   el.dispatchEvent(new CustomEvent(eventType, { detail })); 
  3.  
  4. // 事例 
  5. triggerEvent(document.getElementById('myId'), 'click'); 
  6. triggerEvent(document.getElementById('myId'), 'click', { username: 'bob' }); 

自定義事件的函數(shù)有 Event、CustomEvent 和 dispatchEvent

  1. // 向 window派發(fā)一個resize內(nèi)置事件 
  2. window.dispatchEvent(new Event('resize')) 
  3.  
  4.  
  5. // 直接自定義事件,使用 Event 構(gòu)造函數(shù): 
  6. var event = new Event('build'); 
  7. var elem = document.querySelector('#id'
  8. // 監(jiān)聽事件 
  9. elem.addEventListener('build'function (e) { ... }, false); 
  10. // 觸發(fā)事件. 
  11. elem.dispatchEvent(event); 

CustomEvent 可以創(chuàng)建一個更高度自定義事件,還可以附帶一些數(shù)據(jù),具體用法如下:

  1. var myEvent = new CustomEvent(eventname, options); 
  2. 其中 options 可以是: 
  3.   detail: { 
  4.     ... 
  5.   }, 
  6.   bubbles: true,    //是否冒泡 
  7.   cancelable: false //是否取消默認(rèn)事件 

其中 detail 可以存放一些初始化的信息,可以在觸發(fā)的時候調(diào)用。其他屬性就是定義該事件是否具有冒泡等等功能。

內(nèi)置的事件會由瀏覽器根據(jù)某些操作進(jìn)行觸發(fā),自定義的事件就需要人工觸發(fā)。

dispatchEvent 函數(shù)就是用來觸發(fā)某個事件:

  1. element.dispatchEvent(customEvent); 

上面代碼表示,在 element 上面觸發(fā) customEvent 這個事件。

  1. // add an appropriate event listener 
  2. obj.addEventListener("cat"function(e) { process(e.detail) }); 
  3.  
  4. // create and dispatch the event 
  5. var event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}}); 
  6. obj.dispatchEvent(event); 
  7. 使用自定義事件需要注意兼容性問題,而使用 jQuery 就簡單多了: 
  8.  
  9. // 綁定自定義事件 
  10. $(element).on('myCustomEvent'function(){}); 
  11.  
  12. // 觸發(fā)事件 
  13. $(element).trigger('myCustomEvent'); 
  14. // 此外,你還可以在觸發(fā)自定義事件時傳遞更多參數(shù)信息: 
  15.  
  16. $( "p" ).on"myCustomEvent"function( event, myName ) { 
  17.   $( this ).text( myName + ", hi there!" ); 
  18. }); 
  19. $( "button" ).click(function () { 
  20.   $( "p" ).trigger"myCustomEvent", [ "John" ] ); 
  21. }); 

16.如何從元素中移除事件監(jiān)聽器?

  1. const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); 
  2.  
  3. const fn = () => console.log('!'); 
  4. document.body.addEventListener('click', fn); 
  5. off(document.body, 'click', fn);  

17.如何獲得給定毫秒數(shù)的可讀格式?

  1. const formatDuration = ms => { 
  2.   if (ms < 0) ms = -ms; 
  3.   const time = { 
  4.     day: Math.floor(ms / 86400000), 
  5.     hour: Math.floor(ms / 3600000) % 24, 
  6.     minute: Math.floor(ms / 60000) % 60, 
  7.     second: Math.floor(ms / 1000) % 60, 
  8.     millisecond: Math.floor(ms) % 1000 
  9.   }; 
  10.   return Object.entries(time
  11.     .filter(val => val[1] !== 0) 
  12.     .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`) 
  13.     .join(', '); 
  14. }; 
  15.  
  16. // 事例 
  17. formatDuration(1001); // '1 second, 1 millisecond' 
  18. formatDuration(34325055574);  
  19. // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds' 

18.如何獲得兩個日期之間的差異(以天為單位)?

  1. const getDaysDiffBetweenDates = (dateInitial, dateFinal) => 
  2.   (dateFinal - dateInitial) / (1000 * 3600 * 24); 
  3.  
  4. // 事例 
  5. getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9 

¨K45K ¨G21G

20.如何對傳遞的URL發(fā)出POST請求?

  1. const httpPost = (url, data, callback, err = console.error) => { 
  2.   const request = new XMLHttpRequest(); 
  3.   request.open('POST', url, true); 
  4.   request.setRequestHeader('Content-type''application/json; charset=utf-8'); 
  5.   request.onload = () => callback(request.responseText); 
  6.   request.onerror = () => err(request); 
  7.   request.send(data); 
  8. }; 
  9.  
  10. const newPost = { 
  11.   userId: 1, 
  12.   id: 1337, 
  13.   title: 'Foo'
  14.   body: 'bar bar bar' 
  15. }; 
  16. const data = JSON.stringify(newPost); 
  17. httpPost( 
  18.   'https://jsonplaceholder.typicode.com/posts'
  19.   data, 
  20.   console.log 
  21. );  
  22.  
  23. // {"userId": 1, "id": 1337, "title""Foo""body""bar bar bar"

21.如何為指定選擇器創(chuàng)建具有指定范圍,步長和持續(xù)時間的計數(shù)器?

  1. const counter = (selector, start, end, step = 1, duration = 2000) => { 
  2.   let current = start, 
  3.     _step = (end - start) * step < 0 ? -step : step, 
  4.     timer = setInterval(() => { 
  5.       current += _step; 
  6.       document.querySelector(selector).innerHTML = current
  7.       if (current >= end) document.querySelector(selector).innerHTML = end
  8.       if (current >= end) clearInterval(timer); 
  9.     }, Math.abs(Math.floor(duration / (end - start)))); 
  10.   return timer; 
  11. }; 
  12.  
  13. // 事例 
  14. counter('#my-id', 1, 1000, 5, 2000);  
  15. // 讓 `id=“my-id”`的元素創(chuàng)建一個2秒計時器 

22.如何將字符串復(fù)制到剪貼板?

  1. const copyToClipboard = str => { 
  2.   const el = document.createElement('textarea'); 
  3.   el.value = str; 
  4.   el.setAttribute('readonly'''); 
  5.   el.style.position = 'absolute'
  6.   el.style.left = '-9999px'
  7.   document.body.appendChild(el); 
  8.   const selected = 
  9.     document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false
  10.   el.select(); 
  11.   document.execCommand('copy'); 
  12.   document.body.removeChild(el); 
  13.   if (selected) { 
  14.     document.getSelection().removeAllRanges(); 
  15.     document.getSelection().addRange(selected); 
  16.   } 
  17. }; 
  18.  
  19. // 事例 
  20. copyToClipboard('Lorem ipsum');  
  21. // 'Lorem ipsum' copied to clipboard 

23.如何確定頁面的瀏覽器選項卡是否聚焦?

  1. const isBrowserTabFocused = () => !document.hidden; 
  2.  
  3. // 事例 
  4. isBrowserTabFocused(); // true 

24.如何創(chuàng)建目錄(如果不存在)?

  1. const fs = require('fs'); 
  2. const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined); 
  3.  
  4. // 事例 
  5. createDirIfNotExists('test');  

這里面的方法大都挺實用,可以解決很多開發(fā)過程問題,大家就好好利用起來吧。

https://dev.to/madarsbiss/20-modern-es6-snippets-to-solve-practical-js-problems-3n83

作者:Madza 譯者:前端小智 來源: dev

本文轉(zhuǎn)載自微信公眾號「大遷世界」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系大遷世界公眾號。

 

責(zé)任編輯:武曉燕 來源: 大遷世界
相關(guān)推薦

2020-03-04 17:38:31

瀏覽器程序員CSS

2021-01-27 07:51:41

JSES6元素

2020-03-22 15:48:14

JavaScriptWeb編程語言

2022-09-21 12:46:39

開發(fā)JavaScrip代碼

2022-10-25 08:02:01

JavaScriptArrayMap

2022-09-23 09:14:28

JavaScriptES6代碼

2017-08-31 14:25:34

前端JavascriptES6

2020-07-01 07:58:20

ES6JavaScript開發(fā)

2022-07-26 09:02:15

ES6ES13ECMAScript

2022-06-01 09:06:58

ES6數(shù)組函數(shù)

2021-08-16 07:05:58

ES6Promise開發(fā)語言

2024-06-26 08:18:08

ES6模板字符串

2015-11-10 12:24:36

創(chuàng)業(yè)問題思路

2023-02-23 16:49:11

ES6技巧

2023-11-23 10:21:11

ECMAScriptJavaScript

2021-07-30 07:10:07

ES6函數(shù)參數(shù)

2021-07-16 07:26:48

ES6javascript開發(fā)語言

2020-04-02 09:01:54

JSES 6開發(fā)

2021-04-20 09:48:48

ES5Es6數(shù)組方法

2021-08-02 05:51:29

foreachES6數(shù)組
點贊
收藏

51CTO技術(shù)棧公眾號