數(shù)組 Array
1、數(shù)組去重
function noRepeat(arr) {
return [...new Set(arr)];
}
2末患、查找數(shù)組最大
function arrayMax(arr) {
return Math.max(...arr);
}
3、查找數(shù)組最小
function arrayMin(arr) {
return Math.min(...arr);
}
4锤窑、返回已size為長度的數(shù)組分割的原數(shù)組
function chunk(arr, size = 1) {
return Array.from(
{
length: Math.ceil(arr.length / size),
},
(v, i) => arr.slice(i * size, i * size + size)
);
}
5璧针、檢查數(shù)組中某元素出現(xiàn)的次數(shù)
function countOccurrences(arr, value) {
return arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0);
}
6、扁平化數(shù)組
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),
[]
);
}
7渊啰、對比兩個數(shù)組并且返回其中不同的元素
function diffrence(arrA, arrB) {
return arrA.filter((v) => !arrB.includes(v));
}
8探橱、返回兩個數(shù)組中相同的元素
function intersection(arr1, arr2) {
return arr2.filter((v) => arr1.includes(v));
}
9、從右刪除 n 個元素
function dropRight(arr, n = 0) {
return n < arr.length ? arr.slice(0, arr.length - n) : [];
}
10绘证、截取第一個符合條件的元素及其以后的元素
function dropElements(arr, fn) {
while (arr.length && !fn(arr[0])) arr = arr.slice(1);
return arr;
}
11隧膏、返回數(shù)組中下標(biāo)間隔 nth 的元素
function everyNth(arr, nth) {
return arr.filter((v, i) => i % nth === nth - 1);
}
12、返回數(shù)組中第 n 個元素(支持負(fù)數(shù))
function nthElement(arr, n = 0) {
return (n >= 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
}
13迈窟、返回數(shù)組頭元素
function head(arr) {
return arr[0];
}
14私植、返回數(shù)組末尾元素
function last(arr) {
return arr[arr.length - 1];
}
15、數(shù)組亂排
function shuffle(arr) {
let array = arr;
let index = array.length;
while (index) {
index -= 1;
let randomIndex = Math.floor(Math.random() * index);
let middleware = array[index];
array[index] = array[randomIndex];
array[randomIndex] = middleware;
}
return array;
}
瀏覽器對象 BOM
1车酣、判讀瀏覽器是否支持 CSS 屬性
/**
* 告知瀏覽器支持的指定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中的形式
// 經(jīng)嘗試,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;
}
/**
* 把有連字符號的字符串轉(zhuǎn)化為駝峰命名法的字符串
*/
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;
// 應(yīng)用每個前綴的情況娘摔,且最后也要應(yīng)用上沒有前綴的情況窄坦,看最后瀏覽器起效的何種情況
// 這就是最好在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);
}
2、當(dāng)前網(wǎng)頁地址
function currentURL() {
return window.location.href;
}
3凳寺、獲取滾動條位置
function getScrollPosition(el = window) {
return {
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop,
};
}
4鸭津、獲取 url 中的參數(shù)
function getURLParameters(url) {
return url
.match(/([^?=&]+)(=([^&]*))/g)
.reduce( (a, v) => (
(a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a
),
{}
);
}
5、頁面跳轉(zhuǎn)肠缨,是否記錄在 history 中
function redirect(url, asLink = true) {
asLink ? (window.location.href = url) : window.location.replace(url);
}
6逆趋、滾動條回到頂部動畫
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);
}
}
7、復(fù)制文本
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);
}
}
8晒奕、檢測設(shè)備類型
function detectDeviceType() { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
)
? "Mobile"
: "Desktop";
}
Cookie
1闻书、增
function setCookie(key, value, expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie =
key +
"=" +
escape(value) +
(expiredays == null ? "" : ";expires=" + exdate.toGMTString());
}
2、刪
function getCookie(name) {
var arr,
reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if ((arr = document.cookie.match(reg))) {
return arr[2];
} else {
return null;
}
}
日期 Date
1脑慧、時間戳轉(zhuǎn)換為時間
- 默認(rèn)為當(dāng)前時間轉(zhuǎn)換結(jié)果
- isMs 為時間戳是否為毫秒
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()}`;
}
文檔對象 DOM
1魄眉、固定滾動條
/**
* 功能描述:一些業(yè)務(wù)場景,如彈框出現(xiàn)時闷袒,需要禁止頁面滾動坑律,這是兼容安卓和 iOS 禁止頁面滾動的解決方案
*/
let scrollTop = 0;
function preventScroll() {
// 存儲當(dāng)前滾動位置
scrollTop = window.scrollY;
// 將可滾動區(qū)域固定定位,可滾動區(qū)域高度為 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);
}
2霜运、判斷當(dāng)前位置是否為頁面底部
- 返回值為 true/false
function bottomVisible() {
return (
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight ||
document.documentElement.clientHeight)
);
}
3脾歇、判斷元素是否在可視范圍內(nèi)
- partiallyVisible 為是否為完全可見
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;
}
4蒋腮、獲取元素 css 樣式
function getStyle(el, ruleName) {
return getComputedStyle(el, null).getPropertyValue(ruleName);
}
5、進(jìn)入全屏
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")); //某個元素進(jìn)入全屏
6藕各、退出全屏
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();
7池摧、全屏事件
document.addEventListener("fullscreenchange", function (e) {
if (document.fullscreenElement) {
console.log("進(jìn)入全屏");
} else {
console.log("退出全屏");
}
});
數(shù)字 Number
1、數(shù)字千分位分割
function commafy(num) {
return num.toString().indexOf(".") !== -1 ?
num.toLocaleString() :
num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
}
2激况、生成隨機(jī)數(shù)
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;
}
}