JavaScript常用方法和封裝詳情
1.字符串相關(guān)
1.1 format方法
在各種編程語言中,字符串的format
方法是比較常見的,以下通過js擴(kuò)展的方式,實現(xiàn)了js版本的format方法。目前貌似還沒有瀏覽器支持這一個方法。
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ù)組中的每一個元素
ie9
以上的瀏覽器,以及其他非IE瀏覽器都支持這一方法。
以下是兼容性的擴(kuò)展寫法:
/** ? ? forEach除了接受一個必須的回調(diào)函數(shù)參數(shù),還可以接受一個可選的上下文參數(shù)(改變回調(diào)函數(shù)里面的this指向)(第2個參數(shù))。 */ if (!Array.prototype.forEach && typeof Array.prototype.forEach !== "function") { ? ? Array.prototype.forEach = function(callback, context) { ? ? ? ?// 遍歷數(shù)組,在每一項上調(diào)用回調(diào)函數(shù),這里使用原生方法驗證數(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 = ['雪碧','可樂','脈動','紅牛','農(nóng)夫山泉']; ? ? ? ?? var context = { ? ? str1 : '【', ? ? str2 : '】' }; ? ? ? ?? drinks.forEach(function(item){ ? ? console.log(this.str1 + item + this.str2); },context);
效果:
這個方法在各大瀏覽器都得到了較好的支持。
1.3 indexOf(searchvalue,fromindex) 查詢數(shù)組中某一個值的下標(biāo)
ie9以上的瀏覽器,以及其他非IE瀏覽器都支持這一方法。
以下是兼容性的擴(kuò)展寫法:
//獲取某元素在數(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
類似的還有lastIndexOf
,用于獲取數(shù)組中某個元素最后一次出現(xiàn)的位置。如果數(shù)組沒有這個元素,則返回-1。
該方法的實現(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; ? }; }
通過這兩個方法,我們可以來做一些有意思的事情了。比如,判斷一個對象是否為數(shù)組?
IE9 以上的瀏覽器,已經(jīng)支持通過Array.isArray()
來驗證一個對象是否為數(shù)組了。
比如:
var result = Array.isArray([]); alert(typeof []);//object alert(result); //true
那么,如果我們自己來實現(xiàn),又該如何做呢?下面給出一個簡單思路,
簡單模擬一下這個過程:
//首先,讓我們來看一看數(shù)組的構(gòu)造器是咋樣的? console.log([].constructor.toString()); ? /* ? ? 打印出來是這樣的: ? ? 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
雖然取巧了點,不過目的確實達(dá)到了。
3.數(shù)組封裝
通過數(shù)組的一些基本方法,我們可以開始自己模擬一下java中的ArrayList
了
代碼如下:
//模擬ArrayList function ArrayList(){ ? ? var arr = []; //用于保存數(shù)據(jù)的數(shù)組 ? ? var length = 0; //數(shù)組的長度,默認(rèn)為0 ? ?? ? ? /** ? ? ?* 判斷是否為空 ? ? ?*/ ? ? this.isEmpty = function(){ ? ? ? ? return length == 0; ? ? } ? ?? ? ? /** ? ? ?* 獲取列表長度 ? ? ?*/ ? ?? ? ? this.size = function(){ ? ? ? ? return length; ? ? } ? ?? ? ? /**? ? ? * 判斷對象中是否包含給定對象 ? ? */? ? ? 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 : 需要刪除的元素 ? ? * 參數(shù)2 ?deleteAll: 是否全部刪除,否則默認(rèn)刪除第一個匹配項 ? ? */ ? ?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ù)索引獲取對應(yīng)的元素 ? ? */ ? ?this.get = function(index){ ? ? if(index > length - 1){ ? ? ? ? return null; ? ? } ? ? return arr[index]; ? ?} ? ? ? ?/** ? ? * 獲取列表數(shù)組 ? ? */ ? ?this.toArray = function(){ ? ? ?return arr; ? ?} ? ? ? ?/** ? ? * 獲取某一個元素的角標(biāo) ? ? * 如果只出現(xiàn)一次,就返回一個數(shù)字,如果大于一次,就返回數(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(); ? ? ?} } ? //測試代碼 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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript實現(xiàn)iframe框架延時加載的方法
這篇文章主要介紹了javascript實現(xiàn)iframe框架延時加載的方法,可基于setTimeout實現(xiàn)這一功能,是非常實用的技巧,需要的朋友可以參考下2014-10-10