JavaScript常用方法和封裝詳情
1.字符串相關(guān)
1.1 format方法
在各種編程語(yǔ)言中,字符串的format
方法是比較常見(jiàn)的,以下通過(guò)js擴(kuò)展的方式,實(shí)現(xiàn)了js版本的format方法。目前貌似還沒(méi)有瀏覽器支持這一個(gè)方法。
if(!String.prototype.format ){ ? ? String.prototype.format = function() { ? ? ? ? var e = arguments; ? ? ? ? return this.replace(/{(\d+)}/g,function(t, n) { ? ? ? ? ? ? return typeof e[n] != "undefined" ? e[n] : t; ? ? ? ? }) ? ? }; }?
例子:
var template = "今天的天氣很{0},大家一起去{1}!"; alert(template.format("晴朗","郊游"));
效果:
2.數(shù)組相關(guān)
1.2 forEach(callback,context) 操作數(shù)組中的每一個(gè)元素
ie9
以上的瀏覽器,以及其他非IE瀏覽器都支持這一方法。
以下是兼容性的擴(kuò)展寫(xiě)法:
/** ? ? forEach除了接受一個(gè)必須的回調(diào)函數(shù)參數(shù),還可以接受一個(gè)可選的上下文參數(shù)(改變回調(diào)函數(shù)里面的this指向)(第2個(gè)參數(shù))。 */ if (!Array.prototype.forEach && typeof Array.prototype.forEach !== "function") { ? ? Array.prototype.forEach = function(callback, context) { ? ? ? ?// 遍歷數(shù)組,在每一項(xiàng)上調(diào)用回調(diào)函數(shù),這里使用原生方法驗(yàn)證數(shù)組。 ? ? ? ?if (Object.prototype.toString.call(this) === "[object Array]") { ? ? ? ? ? ?var i,len; ? ? ? ? ? ?//遍歷該數(shù)組所有的元素 ? ? ? ? ? ?for (i = 0, len = this.length; i < len; i++) { ? ? ? ? ? ? ? ?if (typeof callback === "function" ?&& Object.prototype.hasOwnProperty.call(this, i)) { ? ? ? ? ? ? ? ? ? ?if (callback.call(context, this[i], i, this) === false) { ? ? ? ? ? ? ? ? ? ? ? ?break; // or return; ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? ?} ? ? ? ? ? ?} ? ? ? ?} ? ? }; }
例子:
var drinks = ['雪碧','可樂(lè)','脈動(dòng)','紅牛','農(nóng)夫山泉']; ? ? ? ?? var context = { ? ? str1 : '【', ? ? str2 : '】' }; ? ? ? ?? drinks.forEach(function(item){ ? ? console.log(this.str1 + item + this.str2); },context);
效果:
這個(gè)方法在各大瀏覽器都得到了較好的支持。
1.3 indexOf(searchvalue,fromindex) 查詢(xún)數(shù)組中某一個(gè)值的下標(biāo)
ie9以上的瀏覽器,以及其他非IE瀏覽器都支持這一方法。
以下是兼容性的擴(kuò)展寫(xiě)法:
//獲取某元素在數(shù)組中第一次出現(xiàn)的下標(biāo) if (!Array.prototype.indexOf) { ? Array.prototype.indexOf = function(searchElement, fromIndex) { ? ? var k; ? ? // 1. Let O be the result of calling ToObject passing ? ? // ? ?the this value as the argument. ? ? if (this == null) { ? ? ? throw new TypeError('"this" is null or not defined'); ? ? } ? ? ? var O = Object(this); ? ? ? // 2. Let lenValue be the result of calling the Get ? ? // ? ?internal method of O with the argument "length". ? ? // 3. Let len be ToUint32(lenValue). ? ? var len = O.length >>> 0; ? ? ? // 4. If len is 0, return -1. ? ? if (len === 0) { ? ? ? return -1; ? ? } ? ? ? // 5. If argument fromIndex was passed let n be ? ? // ? ?ToInteger(fromIndex); else let n be 0. ? ? var n = +fromIndex || 0; ? ? ? if (Math.abs(n) === Infinity) { ? ? ? n = 0; ? ? } ? ? ? // 6. If n >= len, return -1. ? ? if (n >= len) { ? ? ? return -1; ? ? } ? ? ? // 7. If n >= 0, then Let k be n. ? ? // 8. Else, n<0, Let k be len - abs(n). ? ? // ? ?If k is less than 0, then let k be 0. ? ? k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); ? ? ? // 9. Repeat, while k < len ? ? while (k < len) { ? ? ? // a. Let Pk be ToString(k). ? ? ? // ? This is implicit for LHS operands of the in operator ? ? ? // b. Let kPresent be the result of calling the ? ? ? // ? ?HasProperty internal method of O with argument Pk. ? ? ? // ? This step can be combined with c ? ? ? // c. If kPresent is true, then ? ? ? // ? ?i. ?Let elementK be the result of calling the Get ? ? ? // ? ? ? ?internal method of O with the argument ToString(k). ? ? ? // ? ii. ?Let same be the result of applying the ? ? ? // ? ? ? ?Strict Equality Comparison Algorithm to ? ? ? // ? ? ? ?searchElement and elementK. ? ? ? // ?iii. ?If same is true, return k. ? ? ? ? ? if (k in O && O[k] === searchElement) { ? ? ? ? ? ? return k; ? ? ? ? ? } ? ? ? ? ? k++; ? ? ? ? } ? ? ? ? return -1; ? ? ? }; ? ? }
例子:
var index = drinks.indexOf('雪碧'); alert(index);//0
類(lèi)似的還有lastIndexOf
,用于獲取數(shù)組中某個(gè)元素最后一次出現(xiàn)的位置。如果數(shù)組沒(méi)有這個(gè)元素,則返回-1。
該方法的實(shí)現(xiàn):
//獲取某元素在數(shù)組中最后一次出現(xiàn)的下標(biāo) if (!Array.prototype.lastIndexOf) { ? ? ? Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) { ? ? 'use strict'; ? ? ? if (this === void 0 || this === null) { ? ? ? throw new TypeError(); ? ? } ? ? ? var n, k, ? ? ? ? t = Object(this), ? ? ? ? len = t.length >>> 0; ? ? if (len === 0) { ? ? ? return -1; ? ? } ? ? ? n = len - 1; ? ? if (arguments.length > 1) { ? ? ? n = Number(arguments[1]); ? ? ? if (n != n) { ? ? ? ? n = 0; ? ? ? } ? ? ? else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) { ? ? ? ? n = (n > 0 || -1) * Math.floor(Math.abs(n)); ? ? ? } ? ? } ? ? ? for (k = n >= 0 ? ? ? ? ? ? Math.min(n, len - 1) ? ? ? ? ? : len - Math.abs(n); k >= 0; k--) { ? ? ? if (k in t && t[k] === searchElement) { ? ? ? ? return k; ? ? ? } ? ? } ? ? return -1; ? }; }
通過(guò)這兩個(gè)方法,我們可以來(lái)做一些有意思的事情了。比如,判斷一個(gè)對(duì)象是否為數(shù)組?
IE9 以上的瀏覽器,已經(jīng)支持通過(guò)Array.isArray()
來(lái)驗(yàn)證一個(gè)對(duì)象是否為數(shù)組了。
比如:
var result = Array.isArray([]); alert(typeof []);//object alert(result); //true
那么,如果我們自己來(lái)實(shí)現(xiàn),又該如何做呢?下面給出一個(gè)簡(jiǎn)單思路,
簡(jiǎn)單模擬一下這個(gè)過(guò)程:
//首先,讓我們來(lái)看一看數(shù)組的構(gòu)造器是咋樣的? console.log([].constructor.toString()); ? /* ? ? 打印出來(lái)是這樣的: ? ? function Array() { [native code] } */
于是便有了
?var Array = function(){ ? } ? Array.isArray = function(obj){ ? ? return obj.constructor.toString().indexOf('Array') != -1; } ? var result = Array.isArray([]);? alert(result); //true
雖然取巧了點(diǎn),不過(guò)目的確實(shí)達(dá)到了。
3.數(shù)組封裝
通過(guò)數(shù)組的一些基本方法,我們可以開(kāi)始自己模擬一下java中的ArrayList
了
代碼如下:
//模擬ArrayList function ArrayList(){ ? ? var arr = []; //用于保存數(shù)據(jù)的數(shù)組 ? ? var length = 0; //數(shù)組的長(zhǎng)度,默認(rèn)為0 ? ?? ? ? /** ? ? ?* 判斷是否為空 ? ? ?*/ ? ? this.isEmpty = function(){ ? ? ? ? return length == 0; ? ? } ? ?? ? ? /** ? ? ?* 獲取列表長(zhǎng)度 ? ? ?*/ ? ?? ? ? this.size = function(){ ? ? ? ? return length; ? ? } ? ?? ? ? /**? ? ? * 判斷對(duì)象中是否包含給定對(duì)象 ? ? */? ? ? this.contains = function(obj){ ? ? ? ? if(arr.indexOf(obj) != -1){ ? ? ? ? ? ? return true; ? ? ? ? } ? ? ? ? return false; ? ? } ? ?? ? ? /**? ? ? * 新增 ? ? */ ? ?this.add = function(obj){ ? ? length = length + 1; ? ? arr.push(obj); ? ?} ? ? ? ?/** ? ? * 刪除 ? ? * 參數(shù)1 ?obj : 需要?jiǎng)h除的元素 ? ? * 參數(shù)2 ?deleteAll: 是否全部刪除,否則默認(rèn)刪除第一個(gè)匹配項(xiàng) ? ? */ ? ?this.remove = function(obj,deleteAll){ ? ? ? ? var len = arr.length; ? ? ? ? for(var i = 0 ;i < len ;i++){ ? ? ? ? ? ? if(arr[i] == obj){ ? ? ? ? ? ? ? ? arr.splice(i,1); ? ? ? ? ? ? ? ? length = length - 1; ? ? ? ? ? ? ? ? if(!deleteAll){ ? ? ? ? ? ? ? ? ? ? break; ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? } ? ?} ? ? ? ? ? ?/** ? ? * 根據(jù)索引獲取對(duì)應(yīng)的元素 ? ? */ ? ?this.get = function(index){ ? ? if(index > length - 1){ ? ? ? ? return null; ? ? } ? ? return arr[index]; ? ?} ? ? ? ?/** ? ? * 獲取列表數(shù)組 ? ? */ ? ?this.toArray = function(){ ? ? ?return arr; ? ?} ? ? ? ?/** ? ? * 獲取某一個(gè)元素的角標(biāo) ? ? * 如果只出現(xiàn)一次,就返回一個(gè)數(shù)字,如果大于一次,就返回?cái)?shù)組 ? ? */ ? ?this.indexOf = function(obj){ ? ? ?var rstArr = []; ? ? ?var count = 0; ? ? ?for(var i = 0 ;i < length ;i++){ ? ? ? ? if(obj == arr[i]){ ? ? ? ? ? ? rstArr[count++] = i; ? ? ? ? } ? ? ?} ? ? ?if(count == 1){ ? ? ? ? return rstArr[0]; ? ? ?} ? ? ?return rstArr; ? ?} ? ? ? ?this.toString = function(){ ? ? return arr.toString(); ? ? ?} } ? //測(cè)試代碼 var list = new ArrayList(); list.add('張三'); list.add('李四'); list.add('王五'); list.add('趙六'); list.add('王五'); console.log(list.size()); console.log(list.toString()); console.log(list.contains('張三')); list.remove('王五',true); //null,undefined,'' console.log(list.toString()); console.log(list.get(0)); console.log(list.get(1)); console.log(list.get(2)); console.log(list.size()); ? console.log(list.toArray()); list.add('張三'); list.add('張三'); console.log(list.toArray()); console.log(list.indexOf('張三')); console.log(list.indexOf('趙六'));
運(yùn)行結(jié)果:
到此這篇關(guān)于JavaScript常用方法和封裝詳情的文章就介紹到這了,更多相關(guān)JavaScript方法和封裝內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
2014最熱門(mén)的JavaScript代碼高亮插件推薦
本文給大家推薦今年最流行最熱門(mén)的7款JavaScript代碼高亮插件,各有優(yōu)缺點(diǎn),大家根據(jù)下面的介紹,選擇最適合自己的一款吧。2014-11-11js實(shí)現(xiàn)鍵盤(pán)控制DIV移動(dòng)的方法
這篇文章主要介紹了js實(shí)現(xiàn)鍵盤(pán)控制DIV移動(dòng)的方法,以實(shí)例形式完整的講述了js控制div移動(dòng)所涉及的css、js與html使用技巧,需要的朋友可以參考下2015-01-01xmlplus組件設(shè)計(jì)系列之樹(shù)(Tree)(9)
xmlplus 是一個(gè)JavaScript框架,用于快速開(kāi)發(fā)前后端項(xiàng)目。這篇文章主要介紹了xmlplus組件設(shè)計(jì)系列之tree,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05深入理解在JS中通過(guò)四種設(shè)置事件處理程序的方法
所有的JavaScript事件處理程序的作用域是在其定義時(shí)的作用域而非調(diào)用時(shí)的作用域中執(zhí)行,并且它們能存取那個(gè)作用域中的任何一個(gè)本地變量。但是HTML標(biāo)簽屬性注冊(cè)處理程序就是一個(gè)例外。看下面四種方式2017-03-03javascript實(shí)現(xiàn)iframe框架延時(shí)加載的方法
這篇文章主要介紹了javascript實(shí)現(xiàn)iframe框架延時(shí)加載的方法,可基于setTimeout實(shí)現(xiàn)這一功能,是非常實(shí)用的技巧,需要的朋友可以參考下2014-10-10