文章摘自269个工具函数库:269个工具函数库下

225.查找数组最大

方案一:Math.max + …

  1. function arrayMax(arr) {
  2. return Math.max(...arr);
  3. }
  4. arrayMax([-1,-4,5,2,0])

方案二:Math.max + apply

  1. function arrayMax(arr) {
  2. return Math.max.apply(Math, arr)
  3. }
  4. arrayMax([-1,-4,5,2,0])

方案三:Math.max + 遍历

  1. function arrayMax(arr) {
  2. return arr.reduce((s,n)=>Math.max(s, n))
  3. }
  4. arrayMax([-1,-4,5,2,0])

方案四:比较、条件运算法 + 遍历

  1. function arrayMax(arr) {
  2. return arr.reduce((s,n)=>s>n?s:n)
  3. }
  4. arrayMax([-1,-4,5,2,0])

方案五:排序

  1. function arrayMax(arr) {
  2. return arr.sort((n,m)=>m-n)[0]
  3. }
  4. arrayMax([-1,-4,5,2,0])

226.查找数组最小

  1. Math.max 换成 Math.min
  2. s>n?s:n 换成 s

  3. (n,m)=>m-n换成(n,m)=>n-m,或者直接取最后一个元素
¨K273K ¨K274K ¨G108G ¨K275K ¨G109G ¨K276K ¨G110G ¨K277K ¨K278K ¨G111G ¨K279K ¨G112G ¨K280K ¨K281K ¨G113G ¨K282K ¨G114G ¨K283K ¨K284K 他原文有问题,以下方法的4,5没有返回 ¨G115G 需要再操作一遍 ¨G116G ¨K285K 算是方案1的变种吧,优化了includes` 的性能。

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

方案一:filter + includes

  1. function intersection(arr1, arr2) {
  2. return arr2.filter((v) => arr1.includes(v));
  3. }
  4. intersection([1,2,3], [3,4,5,2])

方案二:同理变种用 hash

  1. function intersection(arr1, arr2) {
  2. var set = new Set(arr2)
  3. return arr1.filter((v) => set.has(v));
  4. }
  5. intersection([1,2,3], [3,4,5,2])

228.从右删除 n 个元素

方案一:slice

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

方案二: splice

  1. function dropRight(arr, n = 0) {
  2. return arr.splice(0, arr.length - n)
  3. }
  4. dropRight([1,2,3,4,5], 2)

方案三: slice 另一种

  1. function dropRight(arr, n = 0) {
  2. return arr.slice(0, -n)
  3. }
  4. dropRight([1,2,3,4,5], 2)

方案四: 修改 length

  1. function dropRight(arr, n = 0) {
  2. arr.length = Math.max(arr.length - n, 0)
  3. return arr
  4. }
  5. dropRight([1,2,3,4,5], 2)

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

方案一:slice + 循环

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

方案二:findIndex + slice

  1. function dropElements(arr, fn) {
  2. return arr.slice(Math.max(arr.findIndex(fn), 0));
  3. }
  4. dropElements([1,2,3,4,5,1,2,3], (v) => v === 3)

方案三:splice + 循环

  1. function dropElements(arr, fn) {
  2. while (arr.length && !fn(arr[0])) arr.splice(0,1);
  3. return arr;
  4. }
  5. dropElements([1,2,3,4,5,1,2,3], (v) => v == 2)

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

方案一:filter

  1. function everyNth(arr, nth) {
  2. return arr.filter((v, i) => i % nth === nth - 1);
  3. }
  4. everyNth([1,2,3,4,5,6,7,8], 2)

方案二:方案一修改判断条件

  1. function everyNth(arr, nth) {
  2. return arr.filter((v, i) => (i+1) % nth === 0);
  3. }
  4. everyNth([1,2,3,4,5,6,7,8], 2)

231.返回数组中第 n 个元素(支持负数)

方案一:slice

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

方案二:三目运算符

  1. function nthElement(arr, n = 0) {
  2. return (n >= 0 ? arr[0] : arr[arr.length + n])
  3. }
  4. nthElement([1,2,3,4,5], 0)
  5. nthElement([1,2,3,4,5], -1)

232.返回数组头元素

方案一:

  1. function head(arr) {
  2. return arr[0];
  3. }
  4. head([1,2,3,4])

方案二:

  1. function head(arr) {
  2. return arr.slice(0,1)[0];
  3. }
  4. head([1,2,3,4])

233.返回数组末尾元素

方案一:

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

方案二:

  1. function last(arr) {
  2. return arr.slice(-1)[0];
  3. }
  4. last([1,2,3,4,5])

234.数组乱排

方案一:洗牌算法

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

方案二:sort + random

  1. function shuffle(arr) {
  2. return arr.sort((n,m)=>Math.random() - .5)
  3. }
  4. shuffle([1,2,3,4,5])

235.伪数组转换为数组

方案一:Array.from

  1. Array.from({length: 2})

方案二:prototype.slice

  1. Array.prototype.slice.call({length: 2,1:1})

方案三:prototype.splice

  1. Array.prototype.splice.call({length: 2,1:1},0)

浏览器对象 BOM

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

```javascript /**

  • 告知浏览器支持的指定css属性情况
  • @param {String} key - css属性,是属性的名字,不需要加前缀
  • @returns {String} - 支持的属性情况 */ function validateCssKey(key) { const jsKey = toCamelCase(key); // 有些css属性是连字符号形成 if (jsKey in document.documentElement.style) { return key; } let validKey = “”; // 属性名为前缀在js中的形式,属性值是前缀在css中的形式 // 经尝试,Webkit 也可是首字母小写 webkit const prefixMap = { Webkit: “-webkit-“, Moz: “-moz-“, ms: “-ms-“, O: “-o-“, }; for (const jsPrefix in prefixMap) { const styleKey = toCamelCase(${jsPrefix}-${jsKey}); if (styleKey in document.documentElement.style) { validKey = prefixMap[jsPrefix] + key; break; } } return validKey; }

/**

  • 把有连字符号的字符串转化为驼峰命名法的字符串 */ function toCamelCase(value) { return value.replace(/-(\w)/g, (matched, letter) => { return letter.toUpperCase(); }); }

/**

  • 检查浏览器是否支持某个css属性值(es6版)
  • @param {String} key - 检查的属性值所属的css属性名
  • @param {String} value - 要检查的css属性值(不要带前缀)
  • @returns {String} - 返回浏览器支持的属性值 */ function valiateCssValue(key, value) { const prefix = [“-o-“, “-ms-“, “-moz-“, “-webkit-“, “”]; const prefixValue = prefix.map((item) => { return item + value; }); const element = document.createElement(“div”); const eleStyle = element.style; // 应用每个前缀的情况,且最后也要应用上没有前缀的情况,看最后浏览器起效的何种情况 // 这就是最好在prefix里的最后一个元素是’’ prefixValue.forEach((item) => { eleStyle[key] = item; }); return eleStyle[key]; }

/**

  • 检查浏览器是否支持某个css属性值
  • @param {String} key - 检查的属性值所属的css属性名
  • @param {String} value - 要检查的css属性值(不要带前缀)
  • @returns {String} - 返回浏览器支持的属性值 */ function valiateCssValue(key, value) { var prefix = [“-o-“, “-ms-“, “-moz-“, “-webkit-“, “”]; var prefixValue = []; for (var i = 0; i < prefix.length; i++) { prefixValue.push(prefix[i] + value); } var element = document.createElement(“div”); var eleStyle = element.style; for (var j = 0; j < prefixValue.length; j++) { eleStyle[key] = prefixValue[j]; } return eleStyle[key]; }

function validCss(key, value) { const validCss = validateCssKey(key); if (validCss) { return validCss; } return valiateCssValue(key, value); }

  1. <a name="Fmbft"></a>
  2. ## 237.返回当前网页地址
  3. <a name="EHm20"></a>
  4. #### 方案一:location
  5. ```javascript
  6. function currentURL() {
  7. return window.location.href;
  8. }
  9. currentURL()

方案二:a 标签

  1. function currentURL() {
  2. var el = document.createElement('a')
  3. el.href = ''
  4. return el.href
  5. }
  6. currentURL()

获取滚动条位置

  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. };
  6. }

238.获取 url 中的参数

方案一:正则 + reduce

  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. );
  10. }
  11. getURLParameters(location.href)

方案二:split + reduce

  1. function getURLParameters(url) {
  2. return url
  3. .split('?') //取?分割
  4. .slice(1) //不要第一部分
  5. .join() //拼接
  6. .split('&')//&分割
  7. .map(v=>v.split('=')) //=分割
  8. .reduce((s,n)=>{s[n[0]] = n[1];return s},{})
  9. }
  10. getURLParameters(location.href)
  11. // getURLParameters('')

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

方案一:

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

方案二:

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

240.滚动条回到顶部动画

方案一: c - c / 8

c 没有定义

  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. }
  10. }
  11. scrollToTop()

修正之后

  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, scrollTop - scrollTop / 8);
  7. } else {
  8. window.cancelAnimationFrame(scrollToTop);
  9. }
  10. }
  11. scrollToTop()

241.复制文本

  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. }
  20. }

242.检测设备类型

方案一: ua

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

方案二:事件属性

  1. function detectDeviceType() {
  2. return ("ontouchstart" in window || navigator.msMaxTouchPoints)
  3. ? "Mobile"
  4. : "Desktop";
  5. }
  6. detectDeviceType()

243.固定滚动条

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

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

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

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

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

246.获取元素 css 样式

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

247.进入全屏

  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")); //某个元素进入全屏

248.退出全屏

  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();

249.全屏事件

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

数字 Number

250.数字千分位分割

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

251.生成随机数

  1. function randomNum(min, max) {
  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. }
  10. }
  11. randomNum(1,10)

252. 时间戳转时间

  1. /* 时间戳转时间 */
  2. function timestampToTime(cjsj) {
  3. var date = new Date(cjsj); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
  4. var Y = date.getFullYear() + '-';
  5. var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  6. var D = (date.getDate() + 1 < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
  7. return Y + M + D
  8. }

253. 过滤富文本和空格为纯文本

  1. /* 过滤富文本和空格为纯文本 */
  2. function filterHtml(str) {
  3. return str.replace(/<[^<>]+>/g, '').replace(/&nbsp;/ig, '');
  4. }

254. 指定显示的文字数量多余的使用省略号代替

  1. /*指定显示的文字数量多余的使用省略号代替*/
  2. function strEllp(str, num = str.length) {
  3. var subStr = str.substring(0, num);
  4. return subStr + (str.length > num ? '...' : '');
  5. }

255. 获取滚动条当前的位置

  1. // 获取滚动条当前的位置
  2. function getScrollTop() {
  3. var scrollTop = 0
  4. if (document.documentElement && document.documentElement.scrollTop) {
  5. scrollTop = document.documentElement.scrollTop;
  6. } else if (document.body) {
  7. scrollTop = document.body.scrollTop;
  8. }
  9. return scrollTop
  10. }

256. 获取当前可视范围的高度

  1. // 获取当前可视范围的高度
  2. function getClientHeight() {
  3. var clientHeight = 0
  4. if (document.body.clientHeight && document.documentElement.clientHeight) {
  5. clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight)
  6. } else {
  7. clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight)
  8. }
  9. return clientHeight
  10. }

257. 获取文档完整的高度

  1. // 获取文档完整的高度
  2. function getScrollHeight() {
  3. return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
  4. }
  • partiallyVisible 为是否为完全可见
  • 返回值为 true/false
  • 默认为当前时间转换结果
  • isMs 为时间戳是否为毫秒
    1. 补位可以改成 padStart
    2. 补位还可以改成 slice