36个工作中常用的JavaScript函数片段

开发 前端
如果文章和笔记能带您一丝帮助或者启发,请不要吝啬你的赞和收藏,你的肯定是我前进的最大动力

[[326015]]

数组 Array

数组去重

 

  1. function noRepeat(arr) { 
  2.   return [...new Set(arr)]; 

查找数组最大

 

  1. function arrayMax(arr) { 
  2.   return Math.max(...arr); 

查找数组最小

 

  1. function arrayMin(arr) { 
  2.   return Math.min(...arr); 

返回已 size 为长度的数组分割的原数组

 

  1. function chunk(arr, size = 1) { 
  2.   return Array.from
  3.     { 
  4.       length: Math.ceil(arr.length / size), 
  5.     }, 
  6.     (v, i) => arr.slice(i * size, i * size + size
  7.   ); 

检查数组中某元素出现的次数

 

  1. function countOccurrences(arr, value) { 
  2.   return arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0); 

扁平化数组

  • 默认 depth 全部展开

 

  1. function flatten(arr, depth = -1) { 
  2.   if (depth === -1) { 
  3.     return [].concat( 
  4.       ...arr.map((v) => (Array.isArray(v) ? this.flatten(v) : v)) 
  5.     ); 
  6.   } 
  7.   if (depth === 1) { 
  8.     return arr.reduce((a, v) => a.concat(v), []); 
  9.   } 
  10.   return arr.reduce( 
  11.     (a, v) => a.concat(Array.isArray(v) ? this.flatten(v, depth - 1) : v), 
  12.     [] 
  13.   ); 

对比两个数组并且返回其中不同的元素

 

  1. function diffrence(arrA, arrB) { 
  2.   return arrA.filter((v) => !arrB.includes(v)); 

返回两个数组中相同的元素

 

  1. function intersection(arr1, arr2) { 
  2.   return arr2.filter((v) => arr1.includes(v)); 

从右删除 n 个元素

 

  1. function dropRight(arr, n = 0) { 
  2.   return n < arr.length ? arr.slice(0, arr.length - n) : []; 

 

截取第一个符合条件的元素及其以后的元素

  1. function dropElements(arr, fn) { 
  2.   while (arr.length && !fn(arr[0])) arr = arr.slice(1); 
  3.   return arr; 

返回数组中下标间隔 nth 的元素

  1. function everyNth(arr, nth) { 
  2.   return arr.filter((v, i) => i % nth === nth - 1); 

返回数组中第 n 个元素

  • 支持负数

 

  1. function nthElement(arr, n = 0) { 
  2.   return (n >= 0 ? arr.slice(n, n + 1) : arr.slice(n))[0]; 

返回数组头元素

 

  1. function head(arr) { 
  2.   return arr[0]; 

返回数组末尾元素

 

  1. function last(arr) { 
  2.   return arr[arr.length - 1]; 

数组乱排

 

  1. function shuffle(arr) { 
  2.   let array = arr; 
  3.   let index = array.length; 
  4.  
  5.   while (index) { 
  6.     index -= 1; 
  7.     let randomInedx = Math.floor(Math.random() * index); 
  8.     let middleware = array[index]; 
  9.     array[index] = array[randomInedx]; 
  10.     array[randomInedx] = middleware; 
  11.   } 
  12.  
  13.   return array; 

浏览器对象 BOM

判读浏览器是否支持 CSS 属性

 

  1. /** 
  2.  * 告知浏览器支持的指定css属性情况 
  3.  * @param {String} key - css属性,是属性的名字,不需要加前缀 
  4.  * @returns {String} - 支持的属性情况 
  5.  */ 
  6. function validateCssKey(key) { 
  7.   const jsKey = toCamelCase(key); // 有些css属性是连字符号形成 
  8.   if (jsKey in document.documentElement.style) { 
  9.     return key
  10.   } 
  11.   let validKey = ""
  12.   // 属性名为前缀在js中的形式,属性值是前缀在css中的形式 
  13.   // 经尝试,Webkit 也可是首字母小写 webkit 
  14.   const prefixMap = { 
  15.     Webkit: "-webkit-"
  16.     Moz: "-moz-"
  17.     ms: "-ms-"
  18.     O: "-o-"
  19.   }; 
  20.   for (const jsPrefix in prefixMap) { 
  21.     const styleKey = toCamelCase(`${jsPrefix}-${jsKey}`); 
  22.     if (styleKey in document.documentElement.style) { 
  23.       validKey = prefixMap[jsPrefix] + key
  24.       break; 
  25.     } 
  26.   } 
  27.   return validKey; 
  28.  
  29. /** 
  30.  * 把有连字符号的字符串转化为驼峰命名法的字符串 
  31.  */ 
  32. function toCamelCase(value) { 
  33.   return value.replace(/-(\w)/g, (matched, letter) => { 
  34.     return letter.toUpperCase(); 
  35.   }); 
  36.  
  37. /** 
  38.  * 检查浏览器是否支持某个css属性值(es6版) 
  39.  * @param {String} key - 检查的属性值所属的css属性名 
  40.  * @param {String} value - 要检查的css属性值(不要带前缀) 
  41.  * @returns {String} - 返回浏览器支持的属性值 
  42.  */ 
  43. function valiateCssValue(key, value) { 
  44.   const prefix = ["-o-""-ms-""-moz-""-webkit-"""]; 
  45.   const prefixValue = prefix.map((item) => { 
  46.     return item + value; 
  47.   }); 
  48.   const element = document.createElement("div"); 
  49.   const eleStyle = element.style; 
  50.   // 应用每个前缀的情况,且最后也要应用上没有前缀的情况,看最后浏览器起效的何种情况 
  51.   // 这就是最好在prefix里的最后一个元素是'' 
  52.   prefixValue.forEach((item) => { 
  53.     eleStyle[key] = item; 
  54.   }); 
  55.   return eleStyle[key]; 
  56.  
  57. /** 
  58.  * 检查浏览器是否支持某个css属性值 
  59.  * @param {String} key - 检查的属性值所属的css属性名 
  60.  * @param {String} value - 要检查的css属性值(不要带前缀) 
  61.  * @returns {String} - 返回浏览器支持的属性值 
  62.  */ 
  63. function valiateCssValue(key, value) { 
  64.   var prefix = ["-o-""-ms-""-moz-""-webkit-"""]; 
  65.   var prefixValue = []; 
  66.   for (var i = 0; i < prefix.length; i++) { 
  67.     prefixValue.push(prefix[i] + value); 
  68.   } 
  69.   var element = document.createElement("div"); 
  70.   var eleStyle = element.style; 
  71.   for (var j = 0; j < prefixValue.length; j++) { 
  72.     eleStyle[key] = prefixValue[j]; 
  73.   } 
  74.   return eleStyle[key]; 
  75.  
  76. function validCss(key, value) { 
  77.   const validCss = validateCssKey(key); 
  78.   if (validCss) { 
  79.     return validCss; 
  80.   } 
  81.   return valiateCssValue(key, value); 
  • 摘自 https://juejin.im/post/5e58f398f265da574a1eb569

返回当前网页地址

 

  1. function currentURL() { 
  2.   return window.location.href; 

获取滚动条位置

 

  1. function getScrollPosition(el = window) { 
  2.   return { 
  3.     x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, 
  4.     y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop, 
  5.   }; 

获取 url 中的参数

 

  1. function getURLParameters(url) { 
  2.   return url 
  3.     .match(/([^?=&]+)(=([^&]*))/g) 
  4.     .reduce( 
  5.       (a, v) => ( 
  6.         (a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a 
  7.       ), 
  8.       {} 
  9.     ); 

页面跳转,是否记录在 history 中

 

  1. function redirect(url, asLink = true) { 
  2.   asLink ? (window.location.href = url) : window.location.replace(url); 

滚动条回到顶部动画

 

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

复制文本

 

  1. function copy(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.   el.style.top = "-9999px"
  8.   document.body.appendChild(el); 
  9.   const selected = 
  10.     document.getSelection().rangeCount > 0 
  11.       ? document.getSelection().getRangeAt(0) 
  12.       : false
  13.   el.select(); 
  14.   document.execCommand("copy"); 
  15.   document.body.removeChild(el); 
  16.   if (selected) { 
  17.     document.getSelection().removeAllRanges(); 
  18.     document.getSelection().addRange(selected); 
  19.   } 

检测设备类型

 

  1. function detectDeviceType() { 
  2.   return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( 
  3.     navigator.userAgent 
  4.   ) 
  5.     ? "Mobile" 
  6.     : "Desktop"

Cookie

 

  1. function setCookie(key, value, expiredays) { 
  2.   var exdate = new Date(); 
  3.   exdate.setDate(exdate.getDate() + expiredays); 
  4.   document.cookie = 
  5.     key + 
  6.     "=" + 
  7.     escape(value) + 
  8.     (expiredays == null ? "" : ";expires=" + exdate.toGMTString()); 

 

  1. function delCookie(name) { 
  2.   var exp = new Date(); 
  3.   exp.setTime(exp.getTime() - 1); 
  4.   var cval = getCookie(name); 
  5.   if (cval != null) { 
  6.     document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString(); 
  7.   } 

 

  1. function getCookie(name) { 
  2.   var arr, 
  3.     reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); 
  4.   if ((arr = document.cookie.match(reg))) { 
  5.     return arr[2]; 
  6.   } else { 
  7.     return null
  8.   } 

日期 Date

时间戳转换为时间

  • 默认为当前时间转换结果
  • isMs 为时间戳是否为毫秒

 

  1. function timestampToTime(timestamp = Date.parse(new Date()), isMs = true) { 
  2.   const date = new Date(timestamp * (isMs ? 1 : 1000)); 
  3.   return `${date.getFullYear()}-${ 
  4.     date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1 
  5.   }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; 

文档对象 DOM

固定滚动条

 

  1. /** 
  2.  * 功能描述:一些业务场景,如弹框出现时,需要禁止页面滚动,这是兼容安卓和 iOS 禁止页面滚动的解决方案 
  3.  */ 
  4.  
  5. let scrollTop = 0; 
  6.  
  7. function preventScroll() { 
  8.   // 存储当前滚动位置 
  9.   scrollTop = window.scrollY; 
  10.  
  11.   // 将可滚动区域固定定位,可滚动区域高度为 0 后就不能滚动了 
  12.   document.body.style["overflow-y"] = "hidden"
  13.   document.body.style.position = "fixed"
  14.   document.body.style.width = "100%"
  15.   document.body.style.top = -scrollTop + "px"
  16.   // document.body.style['overscroll-behavior'] = 'none' 
  17.  
  18. function recoverScroll() { 
  19.   document.body.style["overflow-y"] = "auto"
  20.   document.body.style.position = "static"
  21.   // document.querySelector('body').style['overscroll-behavior'] = 'none' 
  22.  
  23.   window.scrollTo(0, scrollTop); 

判断当前位置是否为页面底部

  • 返回值为 true/false

 

  1. function bottomVisible() { 
  2.   return ( 
  3.     document.documentElement.clientHeight + window.scrollY >= 
  4.     (document.documentElement.scrollHeight || 
  5.       document.documentElement.clientHeight) 
  6.   ); 

判断元素是否在可视范围内

  • partiallyVisible 为是否为完全可见

 

  1. function elementIsVisibleInViewport(el, partiallyVisible = false) { 
  2.   const { topleft, bottom, right } = el.getBoundingClientRect(); 
  3.  
  4.   return partiallyVisible 
  5.     ? ((top > 0 && top < innerHeight) || 
  6.         (bottom > 0 && bottom < innerHeight)) && 
  7.         ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) 
  8.     : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; 

获取元素 css 样式

 

  1. function getStyle(el, ruleName) { 
  2.   return getComputedStyle(el, null).getPropertyValue(ruleName); 

进入全屏

 

  1. function launchFullscreen(element) { 
  2.   if (element.requestFullscreen) { 
  3.     element.requestFullscreen(); 
  4.   } else if (element.mozRequestFullScreen) { 
  5.     element.mozRequestFullScreen(); 
  6.   } else if (element.msRequestFullscreen) { 
  7.     element.msRequestFullscreen(); 
  8.   } else if (element.webkitRequestFullscreen) { 
  9.     element.webkitRequestFullScreen(); 
  10.   } 
  11.  
  12. launchFullscreen(document.documentElement); 
  13. launchFullscreen(document.getElementById("id")); //某个元素进入全屏 

退出全屏

 

  1. function exitFullscreen() { 
  2.   if (document.exitFullscreen) { 
  3.     document.exitFullscreen(); 
  4.   } else if (document.msExitFullscreen) { 
  5.     document.msExitFullscreen(); 
  6.   } else if (document.mozCancelFullScreen) { 
  7.     document.mozCancelFullScreen(); 
  8.   } else if (document.webkitExitFullscreen) { 
  9.     document.webkitExitFullscreen(); 
  10.   } 
  11.  
  12. exitFullscreen(); 

全屏事件

 

  1. document.addEventListener("fullscreenchange"function (e) { 
  2.   if (document.fullscreenElement) { 
  3.     console.log("进入全屏"); 
  4.   } else { 
  5.     console.log("退出全屏"); 
  6.   } 
  7. }); 

数字 Number

数字千分位分割

 

  1. function commafy(num) { 
  2.   return num.toString().indexOf(".") !== -1 
  3.     ? num.toLocaleString() 
  4.     : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,"); 

生成随机数

 

  1. function randomNum(minmax) { 
  2.   switch (arguments.length) { 
  3.     case 1: 
  4.       return parseInt(Math.random() * min + 1, 10); 
  5.     case 2: 
  6.       return parseInt(Math.random() * (max - min + 1) + min, 10); 
  7.     default
  8.       return 0; 
  9.   } 

 

 

责任编辑:华轩 来源: SegmentFault
相关推荐

2017-11-21 15:34:15

Linux 开发开源

2023-11-26 17:47:00

数据分析

2021-08-28 11:47:52

json解析

2019-08-07 16:50:38

SQLjoingroup

2021-10-27 17:57:35

设计模式场景

2024-01-05 09:13:35

2021-09-23 15:13:02

Spring依赖Java

2022-12-13 08:23:25

CSS前端渐变

2021-05-22 23:08:08

深度学习函数算法

2023-06-13 15:15:02

JavaScript前端编程语言

2023-03-30 08:00:56

MySQL日期函数

2010-04-01 09:46:04

Oracle日期函数

2022-09-30 09:26:35

JavaScript技巧

2021-08-26 09:01:16

git 分布式Apache Subv

2022-09-25 22:56:52

JavaScrip编程技巧

2022-04-25 14:27:05

Pandas函数数据

2023-10-10 16:16:05

JavaScrip开发

2023-10-09 14:48:06

2019-09-10 16:54:23

程序员编程语言Java

2023-04-11 08:49:42

排序函数SQL
点赞
收藏

51CTO技术栈公众号