溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

36個工作中常用的JavaScript函數(shù)片段分別是怎樣的

發(fā)布時間:2021-09-30 15:37:38 來源:億速云 閱讀:162 作者:柒染 欄目:web開發(fā)

本篇文章給大家分享的是有關36個工作中常用的JavaScript函數(shù)片段分別是怎樣的,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

數(shù)組 Array

數(shù)組去重

functionnoRepeat(arr){

return[...newSet(arr)];

}

查找數(shù)組最大

functionarrayMax(arr){

returnMath.max(...arr);

}

查找數(shù)組最小

functionarrayMin(arr){

returnMath.min(...arr);

}

返回已 size 為長度的數(shù)組分割的原數(shù)組

functionchunk(arr, size = 1){

returnArray.from(

{

length:Math.ceil(arr.length / size),

},

(v, i) =>arr.slice(i * size, i * size + size)

);

}

檢查數(shù)組中某元素出現(xiàn)的次數(shù)

functioncountOccurrences(arr, value){

returnarr.reduce((a, v) =>(v === value ? a +1: a +0),0);

}

扁平化數(shù)組

默認 depth 全部展開

functionflatten(arr, depth =-1){

if(depth ===-1) {

return[].concat(

...arr.map((v) =>(Array.isArray(v) ?this.flatten(v) :v))

    );

  }

if(depth ===1) {

returnarr.reduce((a, v) =>a.concat(v), []);

}

returnarr.reduce(

(a, v) =>a.concat(Array.isArray(v) ?this.flatten(v, depth -1) : v),

[]

);

}

對比兩個數(shù)組并且返回其中不同的元素

在這里小編建了一個前端學習交流扣扣群:132667127,我自己整理的最新的前端資料和高級開發(fā)教程,如果有想需要的,可以加群一起學習交流

functiondiffrence(arrA, arrB){

returnarrA.filter((v) =>!arrB.includes(v));

}

返回兩個數(shù)組中相同的元素

functionintersection(arr1, arr2){

returnarr2.filter((v) =>arr1.includes(v));

}

從右刪除 n 個元素

functiondropRight(arr, n =0){

returnn < arr.length ? arr.slice(0, arr.length - n) : [];

}

截取第一個符合條件的元素及其以后的元素

functiondropElements(arr, fn){

while(arr.length && !fn(arr[0])) arr = arr.slice(1);

returnarr;

}

返回數(shù)組中下標間隔 nth 的元素

functioneveryNth(arr, nth){

returnarr.filter((v, i) =>i % nth === nth -1);

}

返回數(shù)組中第 n 個元素

支持負數(shù)

functionnthElement(arr, n =0){

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

}

返回數(shù)組頭元素

functionhead(arr){

returnarr[0];

}

返回數(shù)組末尾元素

functionlast(arr){

returnarr[arr.length -1];

}

數(shù)組亂排

functionshuffle(arr){

letarray= 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;

}

returnarray;

}

瀏覽器對象 BOM

判讀瀏覽器是否支持 CSS 屬性

/**

* 告知瀏覽器支持的指定css屬性情況

* @param {String} key - css屬性,是屬性的名字,不需要加前綴

* @returns {String} - 支持的屬性情況

*/

functionvalidateCssKey(key){

const jsKey = toCamelCase(key); // 有些css屬性是連字符號形成

if(jsKeyindocument.documentElement.style) {

returnkey;

}

let validKey ="";

// 屬性名為前綴在js中的形式,屬性值是前綴在css中的形式

// 經(jīng)嘗試,Webkit 也可是首字母小寫 webkit

const prefixMap = {

Webkit:"-webkit-",

Moz:"-moz-",

ms:"-ms-",

O:"-o-",

};

for(const jsPrefixinprefixMap) {

const styleKey = toCamelCase(`${jsPrefix}-${jsKey}`);

if(styleKeyindocument.documentElement.style) {

validKey = prefixMap[jsPrefix] + key;

break;

}

}

returnvalidKey;

}

/**

* 把有連字符號的字符串轉化為駝峰命名法的字符串

*/

functiontoCamelCase(value){

returnvalue.replace(/-(\w)/g, (matched, letter) => {

returnletter.toUpperCase();

});

}

/**

* 檢查瀏覽器是否支持某個css屬性值(es6版)

* @param {String} key - 檢查的屬性值所屬的css屬性名

* @param {String} value - 要檢查的css屬性值(不要帶前綴)

* @returns {String} - 返回瀏覽器支持的屬性值

*/

functionvaliateCssValue(key, value){

const prefix = ["-o-","-ms-","-moz-","-webkit-",""];

const prefixValue = prefix.map((item) => {

returnitem + value;

});

const element = document.createElement("div");

const eleStyle = element.style;

// 應用每個前綴的情況,且最后也要應用上沒有前綴的情況,看最后瀏覽器起效的何種情況

// 這就是最好在prefix里的最后一個元素是''

prefixValue.forEach((item) => {

eleStyle[key] = item;

});

returneleStyle[key];

}

/**

* 檢查瀏覽器是否支持某個css屬性值

* @param {String} key - 檢查的屬性值所屬的css屬性名

* @param {String} value - 要檢查的css屬性值(不要帶前綴)

* @returns {String} - 返回瀏覽器支持的屬性值

*/

functionvaliateCssValue(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];

}

returneleStyle[key];

}

functionvalidCss(key, value){

const validCss = validateCssKey(key);

if(validCss) {

returnvalidCss;

}

returnvaliateCssValue(key, value);

}

返回當前網(wǎng)頁地址

functioncurrentURL(){

returnwindow.location.href;

}

獲取滾動條位置

functiongetScrollPosition(el = window){

return{

x: el.pageXOffset !==undefined? el.pageXOffset : el.scrollLeft,

y: el.pageYOffset !==undefined? el.pageYOffset : el.scrollTop,

};

}

獲取 url 中的參數(shù)

functiongetURLParameters(url){

returnurl

.match(/([^?=&]+)(=([^&]*))/g)

.reduce(

(a, v) =>(

(a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") +1)), a

),

{}

);

}

頁面跳轉,是否記錄在 history 中

functionredirect(url, asLink = true){

asLink ? (window.location.href = url) :window.location.replace(url);

}

滾動條回到頂部動畫

functionscrollToTop(){

constscrollTop =

document.documentElement.scrollTop ||document.body.scrollTop;

if(scrollTop >0) {

window.requestAnimationFrame(scrollToTop);

window.scrollTo(0, c - c /8);

}else{

window.cancelAnimationFrame(scrollToTop);

}

}

復制文本

functioncopy(str){

constel =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);

constselected =

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

}

}

檢測設備類型

functiondetectDeviceType(){

return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(

navigator.userAgent

)

?"Mobile"

:"Desktop";

}

Cookie

functionsetCookie(key, value, expiredays){

varexdate =newDate();

exdate.setDate(exdate.getDate() + expiredays);

document.cookie =

key +

"="+

escape(value) +

(expiredays ==null?"":";expires="+ exdate.toGMTString());

}

functiondelCookie(name){

varexp =newDate();

exp.setTime(exp.getTime() -1);

varcval = getCookie(name);

if(cval !=null) {

document.cookie = name +"="+ cval +";expires="+ exp.toGMTString();

}

}

functiongetCookie(name){

vararr,

reg =newRegExp("(^| )"+ name +"=([^;]*)(;|$)");

if((arr =document.cookie.match(reg))) {

returnarr[2];

}else{

returnnull;

}

}

日期 Date

時間戳轉換為時間

默認為當前時間轉換結果

isMs 為時間戳是否為毫秒

functiontimestampToTime(timestamp =Date.parse(newDate()), isMs =true){

constdate =newDate(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

固定滾動條

/**

* 功能描述:一些業(yè)務場景,如彈框出現(xiàn)時,需要禁止頁面滾動,這是兼容安卓和 iOS 禁止頁面滾動的解決方案

*/

let scrollTop =0;

functionpreventScroll(){

// 存儲當前滾動位置

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'

}

functionrecoverScroll(){

document.body.style["overflow-y"] ="auto";

document.body.style.position ="static";

// document.querySelector('body').style['overscroll-behavior'] ='none'

window.scrollTo(0, scrollTop);

}

判斷當前位置是否為頁面底部

返回值為 true/false

functionbottomVisible(){

return(

document.documentElement.clientHeight +window.scrollY >=

(document.documentElement.scrollHeight ||

document.documentElement.clientHeight)

);

}

判斷元素是否在可視范圍內

partiallyVisible 為是否為完全可見

function elementIsVisibleInViewport(el, partiallyVisible =false) {

const { top,left, bottom,right} = el.getBoundingClientRect();

returnpartiallyVisible

? ((top >0&& top < innerHeight) ||

(bottom >0&& bottom < innerHeight)) &&

((left>0&&left< innerWidth) || (right>0&&right< innerWidth))

: top >=0&&left>=0&& bottom <= innerHeight &&right<= innerWidth;

}

獲取元素 css 樣式

functiongetStyle(el, ruleName){

returngetComputedStyle(el,null).getPropertyValue(ruleName);

}

進入全屏

functionlaunchFullscreen(element) {

if(element.requestFullscreen) {

element.requestFullscreen();

}elseif(element.mozRequestFullScreen) {

element.mozRequestFullScreen();

}elseif(element.msRequestFullscreen) {

element.msRequestFullscreen();

}elseif(element.webkitRequestFullscreen) {

element.webkitRequestFullScreen();

}

}

launchFullscreen(document.documentElement);

launchFullscreen(document.getElementById("id"));//某個元素進入全屏

退出全屏

functionexitFullscreen(){

if(document.exitFullscreen) {

document.exitFullscreen();

}elseif(document.msExitFullscreen) {

document.msExitFullscreen();

}elseif(document.mozCancelFullScreen) {

document.mozCancelFullScreen();

}elseif(document.webkitExitFullscreen) {

document.webkitExitFullscreen();

}

}

exitFullscreen();

全屏事件

document.addEventListener("fullscreenchange",function(e){

if(document.fullscreenElement) {

console.log("進入全屏");

}else{

console.log("退出全屏");

}

});

數(shù)字 Number

數(shù)字千分位分割

functioncommafy(num){

returnnum.toString().indexOf(".") !==-1

? num.toLocaleString()

: num.toString().replace(/(\d)(?=(?:\d{3})+$)/g,"$1,");

}

生成隨機數(shù)

functionrandomNum(min, max){

switch(arguments.length) {

case1:

returnparseInt(Math.random() * min +1,10);

case2:

returnparseInt(Math.random() * (max - min +1) + min,10);

default:

return0;

}

}

以上就是36個工作中常用的JavaScript函數(shù)片段分別是怎樣的,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI