前言
為北關(guān)等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及北關(guān)網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為網(wǎng)站制作、成都網(wǎng)站制作、北關(guān)網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!
在JavaScript中,幾乎每次編寫一段代碼時,通常都會寫入一個函數(shù)。我們的大部分代碼執(zhí)行都是函數(shù)調(diào)用的結(jié)果。所以本文主要給大家介紹了一些JavaScript常用的函數(shù),下面話不多說了,來一起看看詳細(xì)的介紹吧
JavaScript常用的函數(shù)
一、bind、call、apply函數(shù)的實現(xiàn)改變函數(shù)的執(zhí)行上下文中的this指向,但不執(zhí)行該函數(shù)(位于Function構(gòu)造函數(shù)的原型對象上的方法)
Function.prototype.myBind = function (target) { if (typeof this !== 'function') { throw Error('myBind is not a function') } var that = this var args1 = [...arguments].slice(1) var func = function () { var args2 = [..arguments].slice(1) return that.apply(target || window, args1.concat(args2)) } return func } Function.prototype.myCall = function (context=window) { if (typeof this !== 'function') { throw Error('myBind is not a function') } context.fn = this var args = [...arguments].slice(1) var result = context.fn(..args) delete context.fn return result } Function.prototype.myApply = function (context=window) { if (typeof this !== 'function') { throw Error('myApply is not a function') } context.fn = this var result if (argument[1]) { result = context.fn(...arguments[1]) } else { result = context.fn() } delete context.fn return result }
二、引用數(shù)據(jù)類型的深拷貝方法的實現(xiàn)
function cloneDeep (target) { function checkType(target) { return Object.prototype.toString.call(target).slice(8, -1) } var result, checkedType = checkType(target) if (checkedType === 'Array') { result = [] } else if (checkedType === 'Object') { result = {} } else { return target } //遞歸遍歷對象或數(shù)組中的屬性值或元素為原始值為止 for (var key in target) { if ( checkType(target[key]) === 'Array' || checkType(target[key]) === 'Object') { result[key] = cloneDeep(target[key]) } else { result[key] = target[key] } } return result }
思路:
三、數(shù)組flat函數(shù)的實現(xiàn)
Array.prototype.flat
四、實現(xiàn)n的階乘
分析:首先找規(guī)律,舉例如3的階乘等于3*2*1,也就是等于n*n-1*n-2的階乘,也就是等于3*2*1的階乘,計算到1的階乘之后,整個計算過程才結(jié)束。分析到很容易想到通過遞歸來實現(xiàn)這個數(shù)的階乘,因為第一,這個計算過程有規(guī)律可循,第二它有最終停止計算的出口,也就是當(dāng)計算到1的時候就停止運(yùn)算,以下通過遞歸來實現(xiàn)
function factorial (num) { if (num < 0) { throw new Error('負(fù)數(shù)沒有階乘') } if (num === 1 || num === 0) { return 1 } return num * factorial(num-1) } factorial(3) //6
五、實現(xiàn)斐波拉契數(shù)列
分析:按照上述階乘的分析過程分析,這里不贅述
function fibonacci (n) { //此方法應(yīng)使用尾遞歸法進(jìn)行優(yōu)化,這里不作優(yōu)化,簡單實現(xiàn) if ( n <= 1 ) {return 1}; return fibonacci(n - 1) + fibonacci(n - 2);}
六、實現(xiàn)一個計算字符串字節(jié)長度的函數(shù)
分析:首先我們要知道英文的字節(jié)長度是1,而中文的字節(jié)長度是2,但是如何判斷當(dāng)前字符位是漢字還是英文呢,通過charCodeAt來判斷當(dāng)前字符位的unicode編碼是否大于255,如何大于255則是漢字,那就給字符串的字節(jié)長度加2,如果小于255則是英文,就給字符串的字節(jié)長度加1,以下按照這個思路實現(xiàn)
function countBytesLength(str){ var length = 0 //首先遍歷傳入的字符串 for(var i = 0; i < str.length; i++) { if (str[i].charCodeAt(i) > 255) { length += 2 } else { length++ } } return length } var str = 'DBCDouble陳' countBytesLength(str) //11
七、實現(xiàn)isNaN函數(shù)
分析:要判斷傳入的值是否是"is not a number"(isNaN全拼),首先進(jìn)行一個數(shù)字的隱式類型轉(zhuǎn)換,通過Number包裝類來實現(xiàn)Number(x),再判斷Numberz(x)的返回值是否是NaN,如果是的話再與NaN進(jìn)行比對,但是由于NaN雖然是number類型的,但是是不能進(jìn)行比較的,所以我們先將Number(x)返回的結(jié)果變成字符串形式,再去判斷,實現(xiàn)如下
function isNaN(num) { var ret = Number(num) ret += '' if (ret === 'NaN') { return true } return false } isNaN('123abc') // true
八、實現(xiàn)數(shù)組的push函數(shù)
分析:首先push函數(shù)是位于Array構(gòu)造函數(shù)的原型對象上的方法,所以要在Array.prototype上去定義,然后再分析push函數(shù)的作用是往數(shù)組的末尾添加元素,可以添加任意個數(shù)的元素,并且最終返回數(shù)組的長度,實現(xiàn)代碼如下
Array.prototype.push = function () { for (var i = 0; i< arguments.length; i++) { this[this.length] = arguments[i] } return this.length }
七、實現(xiàn)能夠識別所有數(shù)據(jù)類型的typeof分
析:首先typeof是位于window對象上的全局方法,所以我們定義完成之后要將其掛載到window上,其次要實現(xiàn)識別所有數(shù)據(jù)類型包括:基本數(shù)據(jù)類型和復(fù)雜數(shù)據(jù)類型(引用數(shù)據(jù)類型),我們需要通過Object.prototype.toString方法去做才唯一能夠最準(zhǔn)確判斷當(dāng)前值為什么數(shù)據(jù)類型,實現(xiàn)代碼如下
window.typeof = function (value) { return Object.prototype.toString.call(val).slice(8, -1) }
八、實現(xiàn)數(shù)組的去重方法
分析:首先因為是給所有數(shù)組實例實現(xiàn)一個去重方法,所以同樣是在原型鏈上進(jìn)行編程
Array.prototype.unique = function () { //這里是利用對象鍵hash值的唯一性來去重 var obj = {} var result = [] for (var i = 0; i < this.length; i++) { if (!obj[this[i]]) { obj[this[i]] = true result.push(this[i]) } } return result } var arr = [1,2,2,3,3] arr.unique() //[1,2,3]
Array.prototype.unique = function () { //利用ES6的Array.prototype.includes var result = [] for (var i = 0; i < this.length; i++) { if (!result.includes(this[i])) { result.push(this[i]) } } return result }
Array.prototype.unique = function () { //利用ES6的Set var result = new Set(this) //生成一個類數(shù)組 return Array.from(result) //通過Array.from將類數(shù)組轉(zhuǎn)換成真正的數(shù)組 }
Array.prototype.unique = function () { //利用Array.prototype.filter返回符合條件的元素 //利用Array.prototype.indexOf返回數(shù)組中第一次出現(xiàn)當(dāng)前元素的索引值 //該方法寫法最為優(yōu)雅,一行代碼搞定,函數(shù)式編程 return this.filter((item, index) => this.indexOf(item) === index) }
九、實現(xiàn)函數(shù)的防抖、節(jié)流
function debounce (fn, wait=300) { var timer return function () { if (timer) { clearTimeOut(timer) } timer = setTimeout({ fn.apply(this, arguments) }, wait) } } function throttle (fn, wait=300) { var prev = +new Date() return function () { var now = +new Date() if (prev - now > 300) { fn.apply(this, arguments) prev = now } } }
十、封裝ajax
function ajax (options) { options = options || {} options.url = options.url || '' options.method = options.method.toUpperCase() || 'GET' options.async = options.async || true options.data = options.data || null options.success = options.success || function () {} var xhr = null if (XMLHttpRequest) { xhr = new XMLHttpRequest() } else { xhr = new ActiveXObject('Microsoft.XMLHTTP') } xhr.open(options.url, options.method, options.async) var postData = [] for (var key in options.data) { postData.push(key + '='+ options.data[key]) } if (options.method === 'POST') { xhr.open(options.method, options.url, options.async ) xhr.send(postData) } else if (options.method === 'GET') { xhr.open(options.mehtod, options.url + postData.join('&'), options.async) xhr.send(null) } xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { options.success(xhr.responseText) } } }
十一、實現(xiàn)new操作符
function ajax (options) { options = options || {} options.url = options.url || '' options.method = options.method.toUpperCase() || 'GET' options.async = options.async || true options.data = options.data || null options.success = options.success || function () {} var xhr = null if (XMLHttpRequest) { xhr = new XMLHttpRequest() } else { xhr = new ActiveXObject('Microsoft.XMLHTTP') } xhr.open(options.url, options.method, options.async) var postData = [] for (var key in options.data) { postData.push(key + '='+ options.data[key]) } if (options.method === 'POST') { xhr.open(options.method, options.url, options.async ) xhr.send(postData) } else if (options.method === 'GET') { xhr.open(options.mehtod, options.url + postData.join('&'), options.async) xhr.send(null) } xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { options.success(xhr.responseText) } } }
十二、常用六種繼承方式
1、原型鏈繼承:子類型的原型對象為父類型的實例對象
function Person (name, age) { this.name = name this.age = age } Person.prototype.setName = function () { console.log(this.name) } function Student (height) { this.height = height } Student.prototype = new Person() var stu = new Student('175') console.log(stu)
2、借用構(gòu)造函數(shù)實現(xiàn)繼承:在子類的構(gòu)造函數(shù)中通過call調(diào)用父類的構(gòu)造函數(shù)實現(xiàn)繼承
function Person (name, age) { this.name = name this.age = age } Person.prototype.setName = function () { console.log(this.name) } function Student (height, age, name) { Person.call(this, age, name) this.height = height } var stu = new Studeng(175, 'cs', 24) console.log(stu)
3、原型鏈+借用構(gòu)造函數(shù)的組合繼承方式:通過在子類構(gòu)造函數(shù)中通過call調(diào)用父類構(gòu)造函數(shù),繼承父類的屬性并保留傳參的優(yōu)點,再通過將父類的實例作為子類的原型對象,實現(xiàn)繼承
function Person (name, age) { this.name = name this.age = age } Person
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對創(chuàng)新互聯(lián)的支持。
網(wǎng)站名稱:一些手寫JavaScript常用的函數(shù)匯總
轉(zhuǎn)載注明:http://muchs.cn/article4/gheoie.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、、標(biāo)簽優(yōu)化、企業(yè)網(wǎng)站制作、品牌網(wǎng)站制作、外貿(mào)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)