Home Web Front-end JS Tutorial Summarize the JS functions commonly used in front-end development (2)

Summarize the JS functions commonly used in front-end development (2)

Aug 21, 2019 pm 05:27 PM
js

本文接上一篇:总结前端开发中常用的JS功能函数(一)

25、unique: 数组去重,返回一个新数组

function unique(arr){
    if(!isArrayLink(arr)){ //不是类数组对象
        return arr
    }
    let result = []
    let objarr = []
    let obj = Object.create(null)
    
    arr.forEach(item => {
        if(isStatic(item)){//是除了symbol外的原始数据
            let key = item + '_' + getRawType(item);
            if(!obj[key]){
                obj[key] = true
                result.push(item)
            }
        }else{//引用类型及symbol
            if(!objarr.includes(item)){
                objarr.push(item)
                result.push(item)
            }
        }
    })
    
    return resulte
}
Copy after login

26、Set简单实现

window.Set = window.Set || (function () {
    function Set(arr) {
        this.items = arr ? unique(arr) : [];
        this.size = this.items.length; // Array的大小
    }
    Set.prototype = {
        add: function (value) {
            // 添加元素,若元素已存在,则跳过,返回 Set 结构本身。
            if (!this.has(value)) {
                this.items.push(value);
                this.size++;
            }
            return this;
        },
        clear: function () {
            //清除所有成员,没有返回值。
            this.items = []
            this.size = 0
        },
        delete: function (value) {
            //删除某个值,返回一个布尔值,表示删除是否成功。
            return this.items.some((v, i) => {
                if(v === value){
                    this.items.splice(i,1)
                    return true
                }
                return false
            })
        },
        has: function (value) {
            //返回一个布尔值,表示该值是否为Set的成员。
            return this.items.some(v => v === value)
        },
        values: function () {
            return this.items
        },
    }

    return Set;
}());
Copy after login

27、repeat:生成一个重复的字符串,有n个str组成,可修改为填充为数组等

function repeat(str, n) {
    let res = '';
    while(n) {
        if(n % 2 === 1) {
            res += str;
        }
        if(n > 1) {
            str += str;
        }
        n >>= 1;
    }
    return res
};
//repeat('123',3) ==> 123123123
Copy after login

28、dateFormater:格式化时间

function dateFormater(formater, t){
    let date = t ? new Date(t) : new Date(),
        Y = date.getFullYear() + '',
        M = date.getMonth() + 1,
        D = date.getDate(),
        H = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds();
    return formater.replace(/YYYY|yyyy/g,Y)
        .replace(/YY|yy/g,Y.substr(2,2))
        .replace(/MM/g,(M<10?&#39;0&#39;:&#39;&#39;) + M)
        .replace(/DD/g,(D<10?&#39;0&#39;:&#39;&#39;) + D)
        .replace(/HH|hh/g,(H<10?&#39;0&#39;:&#39;&#39;) + H)
        .replace(/mm/g,(m<10?&#39;0&#39;:&#39;&#39;) + m)
        .replace(/ss/g,(s<10?&#39;0&#39;:&#39;&#39;) + s)
}
// dateFormater(&#39;YYYY-MM-DD HH:mm&#39;, t) ==> 2019-06-26 18:30
// dateFormater(&#39;YYYYMMDDHHmm&#39;, t) ==> 201906261830
Copy after login

29、dateStrForma:将指定字符串由一种时间格式转化为另一种。From的格式应对应str的位置

function dateStrForma(str, from, to){
    //&#39;20190626&#39; &#39;YYYYMMDD&#39; &#39;YYYY年MM月DD日&#39;
    str += &#39;&#39;
    let Y = &#39;&#39;
    if(~(Y = from.indexOf(&#39;YYYY&#39;))){
        Y = str.substr(Y, 4)
        to = to.replace(/YYYY|yyyy/g,Y)
    }else if(~(Y = from.indexOf(&#39;YY&#39;))){
        Y = str.substr(Y, 2)
        to = to.replace(/YY|yy/g,Y)
    }

    let k,i
    [&#39;M&#39;,&#39;D&#39;,&#39;H&#39;,&#39;h&#39;,&#39;m&#39;,&#39;s&#39;].forEach(s =>{
        i = from.indexOf(s+s)
        k = ~i ? str.substr(i, 2) : &#39;&#39;
        to = to.replace(s+s, k)
    })
    return to
}
// dateStrForma(&#39;20190626&#39;, &#39;YYYYMMDD&#39;, &#39;YYYY年MM月DD日&#39;) ==> 2019年06月26日
// dateStrForma(&#39;121220190626&#39;, &#39;----YYYYMMDD&#39;, &#39;YYYY年MM月DD日&#39;) ==> 2019年06月26日
// dateStrForma(&#39;2019年06月26日&#39;, &#39;YYYY年MM月DD日&#39;, &#39;YYYYMMDD&#39;) ==> 20190626

// 一般的也可以使用正则来实现
//&#39;2019年06月26日&#39;.replace(/(\d{4})年(\d{2})月(\d{2})日/, &#39;$1-$2-$3&#39;) ==> 2019-06-26
Copy after login

30、getPropByPath:根据字符串路径获取对象属性:‘obj[0].count

function getPropByPath(obj, path, strict) {
      let tempObj = obj;
      path = path.replace(/\[(\w+)\]/g, &#39;.$1&#39;); //将[0]转化为.0
      path = path.replace(/^\./, &#39;&#39;); //去除开头的.

      let keyArr = path.split(&#39;.&#39;); //根据.切割
      let i = 0;
      for (let len = keyArr.length; i < len - 1; ++i) {
        if (!tempObj && !strict) break;
        let key = keyArr[i];
        if (key in tempObj) {
            tempObj = tempObj[key];
        } else {
            if (strict) {//开启严格模式,没找到对应key值,抛出错误
                throw new Error(&#39;please transfer a valid prop path to form item!&#39;);
            }
            break;
        }
      }
      return {
        o: tempObj, //原始数据
        k: keyArr[i], //key值
        v: tempObj ? tempObj[keyArr[i]] : null // key值对应的值
      };
};
Copy after login

31、GetUrlParam:获取Url参数,返回一个对象

function GetUrlParam(){
    let url = document.location.toString();
    let arrObj = url.split("?");
    let params = Object.create(null)
    if (arrObj.length > 1){
        arrObj = arrObj[1].split("&");
        arrObj.forEach(item=>{
            item = item.split("=");
            params[item[0]] = item[1]
        })
    }
    return params;
}
// ?a=1&b=2&c=3 ==> {a: "1", b: "2", c: "3"}
Copy after login

32、downloadFile:base64数据导出文件,文件下载

function downloadFile(filename, data) {
	let DownloadLink = document.createElement(&#39;a&#39;);
	if (DownloadLink) {
		document.body.appendChild(DownloadLink);
		DownloadLink.style = &#39;display: none&#39;;
		DownloadLink.download = filename;
		DownloadLink.href = data;
		if (document.createEvent) {
			let DownloadEvt = document.createEvent(&#39;MouseEvents&#39;);
			DownloadEvt.initEvent(&#39;click&#39;, true, false);
			DownloadLink.dispatchEvent(DownloadEvt);
		} else if (document.createEventObject) {
			DownloadLink.fireEvent(&#39;onclick&#39;);
		} else if (typeof DownloadLink.onclick == &#39;function&#39;) {
			DownloadLink.onclick();
		}
		document.body.removeChild(DownloadLink);
	}
}
Copy after login

33、toFullScreen:全屏

function toFullScreen() {
	let elem = document.body;
    elem.webkitRequestFullScreen
    ? elem.webkitRequestFullScreen()
    : elem.mozRequestFullScreen
    ? elem.mozRequestFullScreen()
    : elem.msRequestFullscreen
    ? elem.msRequestFullscreen()
    : elem.requestFullScreen
    ? elem.requestFullScreen()
    : alert("浏览器不支持全屏");
}
Copy after login

34、exitFullscreen:退出全屏

function exitFullscreen() {
	let elem = parent.document;
	elem.webkitCancelFullScreen
	? elem.webkitCancelFullScreen()
	: elem.mozCancelFullScreen
	? elem.mozCancelFullScreen()
    : elem.cancelFullScreen
    ? elem.cancelFullScreen()
    : elem.msExitFullscreen
    ? elem.msExitFullscreen()
    : elem.exitFullscreen
    ? elem.exitFullscreen()
    : alert("切换失败,可尝试Esc退出");
}
Copy after login

35、requestAnimationFrame:window动画

window.requestAnimationFrame = window.requestAnimationFrame ||
	window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    function (callback) {
		//为了使setTimteout的尽可能的接近每秒60帧的效果
		window.setTimeout(callback, 1000 / 60);
	}
window.cancelAnimationFrame = window.cancelAnimationFrame ||
	window.webkitCancelAnimationFrame ||
    window.mozCancelAnimationFrame ||
    window.msCancelAnimationFrame ||
    window.oCancelAnimationFrame ||
    function (id) {
		//为了使setTimteout的尽可能的接近每秒60帧的效果
        window.clearTimeout(id);
	}
Copy after login

36、_isNaN:检查数据是否是非数字值

function _isNaN(v){
    return !(typeof v === &#39;string&#39; || typeof v === &#39;number&#39;) || isNaN(v)
}
Copy after login

37、max:求取数组中非NaN数据中的最大值

function max(arr){
    arr = arr.filter(item => !_isNaN(item))
    return arr.length ? Math.max.apply(null, arr) : undefined
}
//max([1, 2, &#39;11&#39;, null, &#39;fdf&#39;, []]) ==> 11
Copy after login

38、min:求取数组中非NaN数据中的最小值

function min(arr){
    arr = arr.filter(item => !_isNaN(item))
    return arr.length ? Math.min.apply(null, arr) : undefined
}
//min([1, 2, &#39;11&#39;, null, &#39;fdf&#39;, []]) ==> 1
Copy after login

39、random:返回一个lower-upper直接的随机数。(lowerupper无论正负与大小,但必须是非NaN的数据)

function random(lower, upper) {
	lower = +lower || 0
	upper = +upper || 0
	return Math.random() * (upper - lower) + lower;
}
//random(0, 0.5) ==> 0.3567039135734613
//random(2, 1) ===> 1.6718418553475423
//random(-2, -1) ==> -1.4474325452361945
Copy after login

40、Object.keys:返回一个由一个给定对象的自身可枚举属性组成的数组

Object.keys = Object.keys || function keys(object) {
	if (object === null || object === undefined) {
		throw new TypeError(&#39;Cannot convert undefined or null to object&#39;);
	}
	let result = [];
	if (isArrayLike(object) || isPlainObject(object)) {
		for (let key in object) {
			object.hasOwnProperty(key) && (result.push(key))
		}
	}
	return result;
}
Copy after login

41、Object.values:返回一个给定对象自身的所有可枚举属性值的数组

Object.values = Object.values || function values(object) {
	if (object === null || object === undefined) {
		throw new TypeError(&#39;Cannot convert undefined or null to object&#39;);
	}
	let result = [];
	if (isArrayLike(object) || isPlainObject(object)) {
		for (let key in object) {
			object.hasOwnProperty(key) && (result.push(object[key]))
		}
	}
	return result;
}
Copy after login

42、arr.fill:使用value值填充array,从start位置开始,到end位置结束(但不包含end位置),返回原数组

Array.prototype.fill = Array.prototype.fill || function fill(value, start, end) {
    let ctx = this
    let length = ctx.length;
    
    start = parseInt(start)
    if(isNaN(start)){
        start = 0
    }else if (start < 0) {
        start = -start > length ? 0 : (length + start);
      }
      
      end = parseInt(end)
      if(isNaN(end) || end > length){
          end = length
      }else if (end < 0) {
        end += length;
    }
    
    while (start < end) {
        ctx[start++] = value;
    }
    return ctx;
}
//Array(3).fill(2) ===> [2, 2, 2]
Copy after login

43、arr.includes:用来判断一个数组是否包含一个指定的值,如果是返回true,否则返回false,可指定开始查询的位置

Array.prototype.includes = Array.prototype.includes || function includes(value, start) {
	let ctx = this;
	let length = ctx.length;
	start = parseInt(start)
	if(isNaN(start)) {
		start = 0
	} else if (start < 0) {
		start = -start > length ? 0 : (length + start);
	}
	let index = ctx.indexOf(value);
	return index >= start;
}
Copy after login

44、返回数组中通过测试(函数fn内判断)的第一个元素的值

Array.prototype.find = Array.prototype.find || function find(fn, ctx) {
	ctx = ctx || this;
	let result;
	ctx.some((value, index, arr), thisValue) => {
		return fn(value, index, arr) ? (result = value, true) : false
	})
	return result
}
Copy after login

45、arr.findIndex:返回数组中通过测试(函数fn内判断)的第一个元素的下标

Array.prototype.findIndex = Array.prototype.findIndex || function findIndex(fn, ctx){
    ctx = ctx || this
    
    let result;
    ctx.some((value, index, arr), thisValue) => {
        return fn(value, index, arr) ? (result = index, true) : false
    })
    
    return result
}
Copy after login

46、performance.timing:利用performance.timing进行性能分析

window.onload = function() {
	setTimeout(function() {
		let t = performance.timing;
		console.log(&#39;DNS查询耗时 :&#39; + (t.domainLookupEnd - t.domainLookupStart).toFixed(0))
        console.log(&#39;TCP链接耗时 :&#39; + (t.connectEnd - t.connectStart).toFixed(0))
        console.log(&#39;request请求耗时 :&#39; + (t.responseEnd - t.responseStart).toFixed(0))
        console.log(&#39;解析dom树耗时 :&#39; + (t.domComplete - t.domInteractive).toFixed(0))
        console.log(&#39;白屏时间 :&#39; + (t.responseStart - t.navigationStart).toFixed(0))
        console.log(&#39;domready时间 :&#39; + (t.domContentLoadedEventEnd - t.navigationStart).toFixed(0))
        console.log(&#39;onload时间 :&#39; + (t.loadEventEnd - t.navigationStart).toFixed(0))
        if (t = performance.memory) {
			console.log(&#39;js内存使用占比:&#39; +  (t.usedJSHeapSize / t.totalJSHeapSize * 100).toFixed(2) + &#39;%&#39;)
		}
	})
}
Copy after login

47、禁止某些键盘事件

document.addEventListener(&#39;keydown&#39;, function(event) {
	return !(
		112 == event.keyCode ||		//禁止F1
		123 == event.keyCode ||		//禁止F12
		event.ctrlKey && 82 == event.keyCode ||		//禁止ctrl+R
		event.ctrlKey && 18 == event.keyCode ||		//禁止ctrl+N
		event.shiftKey && 121 == event.keyCode ||  		//禁止shift+F10
		event.altKey && 115 == event.keyCode ||		//禁止alt+F4
		"A" == event.srcElement.tagName && event.shiftKey		//禁止shift+点击a标签
	) || (event.returnValue = false)
});
Copy after login

48、禁止右键、选择、复制

[&#39;contextmenu&#39;, &#39;selectstart&#39;, &#39;copy&#39;].forEach(function(ev) {
	document.addEventListener(ev, function(event) {
		return event.returnValue = false;
	})
});
Copy after login

以上两篇文章就是整理的48个前端开发常用函数,欢迎大家继续补充。谢谢!

更多JavaScript相关内容请访问PHP中文网:https://www.php.cn/

The above is the detailed content of Summarize the JS functions commonly used in front-end development (2). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles