最近在思否看到一個文章36個工做中經常使用的JavaScript函數片斷。css
身爲坑爹面試官(▄█▀█●),怎麼能只有一個答案呢?html
Set + ...
function noRepeat(arr) { return [...new Set(arr)]; } noRepeat([1,2,3,1,2,3])
Set + Array.from
function noRepeat(arr) { return Array.from(new Set(arr)); } noRepeat([1,2,3,1,2,3])
function noRepeat(arr) { return arr.filter((v, idx)=>idx == arr.lastIndexOf(v)) } noRepeat([1,2,3,1,2,3])
Object 的特性是 Key 不會重複。
這裏使用 values 是由於能夠保留類型,keys 會變成字符串。前端
function noRepeat(arr) { return Object.values(arr.reduce((s,n)=>{ s[n] = n; return s },{})) } noRepeat([1,2,3,1,2,3])
針對於上述的方案,還有其餘變種實現。es6
Math.max + ...
function arrayMax(arr) { return Math.max(...arr); } arrayMax([-1,-4,5,2,0])
Math.max + apply
function arrayMax(arr) { return Math.max.apply(Math, arr) } arrayMax([-1,-4,5,2,0])
Math.max
+ 遍歷function arrayMax(arr) { return arr.reduce((s,n)=>Math.max(s, n)) } arrayMax([-1,-4,5,2,0])
function arrayMax(arr) { return arr.reduce((s,n)=>s>n?s:n) } arrayMax([-1,-4,5,2,0])
function arrayMax(arr) { return arr.sort((n,m)=>m-n)[0] } arrayMax([-1,-4,5,2,0])
同上,不明白爲何要分紅兩個題目。web
Math.max
換成 Math.min
s>n?s:n
換成 s<n?s:n
(n,m)=>m-n
換成 (n,m)=>n-m
,或者直接取最後一個元素function chunk(arr, size = 1) { return Array.from( { length: Math.ceil(arr.length / size), }, (v, i) => arr.slice(i * size, i * size + size) ); } chunk([1,2,3,4,5,6,7,8],3)
function chunk(arr, size = 1) { return Array.from( { length: Math.ceil(arr.length / size), }, (v, i) => arr.splice(0, size) ); } chunk([1,2,3,4,5,6,7,8],3)
function chunk(arr, size = 1) { var _returnArr = []; while(arr.length){ _returnArr.push(arr.splice(0, size)) } return _returnArr } chunk([1,2,3,4,5,6,7,8],3)
function countOccurrences(arr, value) { return arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0); } countOccurrences([1,2,3,4,5,1,2,1,2,3], 1)
function countOccurrences(arr, value) { return arr.filter(v=>v===value).length } countOccurrences([1,2,3,4,5,1,2,1,2,3], 1)
function flatten(arr, depth = -1) { if (depth === -1) { return [].concat( ...arr.map((v) => (Array.isArray(v) ? this.flatten(v) : v)) ); } if (depth === 1) { return arr.reduce((a, v) => a.concat(v), []); } return arr.reduce( (a, v) => a.concat(Array.isArray(v) ? this.flatten(v, depth - 1) : v), [] ); } flatten([1,[2,[3]]])
function flatten(arr, depth = Infinity) { return arr.flat(depth) } flatten([1,[2,[3]]])
他原文有問題,如下方法的 4,5
沒有返回面試
function diffrence(arrA, arrB) { return arrA.filter((v) => !arrB.includes(v)); } diffrence([1,2,3], [3,4,5,2])
須要再操做一遍算法
function diffrence(arrA, arrB) { return arrA.filter((v) => !arrB.includes(v)) .concat(arrB.filter((v) => !arrA.includes(v))); } diffrence([1,2,3], [3,4,5,2])
算是方案1的變種吧,優化了 includes
的性能。segmentfault
function intersection(arr1, arr2) { return arr2.filter((v) => arr1.includes(v)); } intersection([1,2,3], [3,4,5,2])
function intersection(arr1, arr2) { var set = new Set(arr2) return arr1.filter((v) => set.has(v)); } intersection([1,2,3], [3,4,5,2])
function dropRight(arr, n = 0) { return n < arr.length ? arr.slice(0, arr.length - n) : []; } dropRight([1,2,3,4,5], 2)
function dropRight(arr, n = 0) { return arr.splice(0, arr.length - n) } dropRight([1,2,3,4,5], 2)
function dropRight(arr, n = 0) { return arr.slice(0, -n) } dropRight([1,2,3,4,5], 2)
function dropRight(arr, n = 0) { arr.length = Math.max(arr.length - n, 0) return arr } dropRight([1,2,3,4,5], 2)
function dropElements(arr, fn) { while (arr.length && !fn(arr[0])) arr = arr.slice(1); return arr; } dropElements([1,2,3,4,5,1,2,3], (v) => v == 2)
function dropElements(arr, fn) { return arr.slice(Math.max(arr.findIndex(fn), 0)); } dropElements([1,2,3,4,5,1,2,3], (v) => v === 3)
function dropElements(arr, fn) { while (arr.length && !fn(arr[0])) arr.splice(0,1); return arr; } dropElements([1,2,3,4,5,1,2,3], (v) => v == 2)
function everyNth(arr, nth) { return arr.filter((v, i) => i % nth === nth - 1); } everyNth([1,2,3,4,5,6,7,8], 2)
function everyNth(arr, nth) { return arr.filter((v, i) => (i+1) % nth === 0); } everyNth([1,2,3,4,5,6,7,8], 2)
function nthElement(arr, n = 0) { return (n >= 0 ? arr.slice(n, n + 1) : arr.slice(n))[0]; } nthElement([1,2,3,4,5], 0) nthElement([1,2,3,4,5], -1)
function nthElement(arr, n = 0) { return (n >= 0 ? arr[0] : arr[arr.length + n]) } nthElement([1,2,3,4,5], 0) nthElement([1,2,3,4,5], -1)
function head(arr) { return arr[0]; } head([1,2,3,4])
function head(arr) { return arr.slice(0,1)[0]; } head([1,2,3,4])
function last(arr) { return arr[arr.length - 1]; }
function last(arr) { return arr.slice(-1)[0]; } last([1,2,3,4,5])
function shuffle(arr) { let array = arr; let index = array.length; while (index) { index -= 1; let randomInedx = Math.floor(Math.random() * index); let middleware = array[index]; array[index] = array[randomInedx]; array[randomInedx] = middleware; } return array; } shuffle([1,2,3,4,5])
function shuffle(arr) { return arr.sort((n,m)=>Math.random() - .5) } shuffle([1,2,3,4,5])
Array.from({length: 2})
Array.prototype.slice.call({length: 2,1:1})
Array.prototype.splice.call({length: 2,1:1},0)
/** * 告知瀏覽器支持的指定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); }
https://segmentfault.com/a/11...
它裏面有 forEach。數組
function currentURL() { return window.location.href; } currentURL()
function currentURL() { var el = document.createElement('a') el.href = '' return el.href } currentURL()
function getScrollPosition(el = window) { return { x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop, }; }
function getURLParameters(url) { return url .match(/([^?=&]+)(=([^&]*))/g) .reduce( (a, v) => ( (a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a ), {} ); } getURLParameters(location.href)
function getURLParameters(url) { return url .split('?') //取?分割 .slice(1) //不要第一部分 .join() //拼接 .split('&')//&分割 .map(v=>v.split('=')) //=分割 .reduce((s,n)=>{s[n[0]] = n[1];return s},{}) } getURLParameters(location.href) // getURLParameters('')
function redirect(url, asLink = true) { asLink ? (window.location.href = url) : window.location.replace(url); }
function redirect(url, asLink = true) { asLink ? window.location.assign(url) : window.location.replace(url); }
c 沒有定義瀏覽器
function scrollToTop() { const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; if (scrollTop > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); } else { window.cancelAnimationFrame(scrollToTop); } } scrollToTop()
修正以後
function scrollToTop() { const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; if (scrollTop > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, scrollTop - scrollTop / 8); } else { window.cancelAnimationFrame(scrollToTop); } } scrollToTop()
function copy(str) { const el = document.createElement("textarea"); el.value = str; el.setAttribute("readonly", ""); el.style.position = "absolute"; el.style.left = "-9999px"; el.style.top = "-9999px"; document.body.appendChild(el); const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; el.select(); document.execCommand("copy"); document.body.removeChild(el); if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); } }
function detectDeviceType() { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent ) ? "Mobile" : "Desktop"; } detectDeviceType()
function detectDeviceType() { return ("ontouchstart" in window || navigator.msMaxTouchPoints) ? "Mobile" : "Desktop"; } detectDeviceType()
function setCookie(key, value, expiredays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + expiredays); document.cookie = key + "=" + escape(value) + (expiredays == null ? "" : ";expires=" + exdate.toGMTString()); }
function delCookie(name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = getCookie(name); if (cval != null) { document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString(); } }
function getCookie(name) { var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); if ((arr = document.cookie.match(reg))) { return arr[2]; } else { return null; } }
有時候咱們想清空,可是又沒法獲取到全部的cookie。
這個時候咱們能夠了利用寫滿,而後再清空的辦法。
function timestampToTime(timestamp = Date.parse(new Date()), isMs = true) { const date = new Date(timestamp * (isMs ? 1 : 1000)); return `${date.getFullYear()}-${ date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1 }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; }
若是作海外的話,還會有時區問題,通常我用moment解決。若是想看原生的
基於上一個想到的問題
/** * 功能描述:一些業務場景,如彈框出現時,須要禁止頁面滾動,這是兼容安卓和 iOS 禁止頁面滾動的解決方案 */ let scrollTop = 0; function preventScroll() { // 存儲當前滾動位置 scrollTop = window.scrollY; // 將可滾動區域固定定位,可滾動區域高度爲 0 後就不能滾動了 document.body.style["overflow-y"] = "hidden"; document.body.style.position = "fixed"; document.body.style.width = "100%"; document.body.style.top = -scrollTop + "px"; // document.body.style['overscroll-behavior'] = 'none' } function recoverScroll() { document.body.style["overflow-y"] = "auto"; document.body.style.position = "static"; // document.querySelector('body').style['overscroll-behavior'] = 'none' window.scrollTo(0, scrollTop); }
function bottomVisible() { return ( document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight) ); }
function elementIsVisibleInViewport(el, partiallyVisible = false) { const { top, left, bottom, right } = el.getBoundingClientRect(); return partiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }
function getStyle(el, ruleName) { return getComputedStyle(el, null).getPropertyValue(ruleName); }
function launchFullscreen(element) { if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullScreen(); } } launchFullscreen(document.documentElement); launchFullscreen(document.getElementById("id")); //某個元素進入全屏
function exitFullscreen() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } } exitFullscreen();
document.addEventListener("fullscreenchange", function (e) { if (document.fullscreenElement) { console.log("進入全屏"); } else { console.log("退出全屏"); } });
function commafy(num) { return num.toString().indexOf(".") !== -1 ? num.toLocaleString() : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,"); } commafy(1000)
function randomNum(min, max) { switch (arguments.length) { case 1: return parseInt(Math.random() * min + 1, 10); case 2: return parseInt(Math.random() * (max - min + 1) + min, 10); default: return 0; } } randomNum(1,10)
歡迎你們關注個人公衆號。有疑問也能夠加個人微信前端交流羣。