溫馨提示×

溫馨提示×

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

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

JavaScript常用方法和封裝實例分析

發(fā)布時間:2022-03-24 16:27:05 來源:億速云 閱讀:99 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹了JavaScript常用方法和封裝實例分析的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇JavaScript常用方法和封裝實例分析文章都會有所收獲,下面我們一起來看看吧。

    1.字符串相關

    1.1 format方法

    在各種編程語言中,字符串的format方法是比較常見的,以下通過js擴展的方式,實現(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("晴朗","郊游"));

    效果:

    JavaScript常用方法和封裝實例分析

    2.數(shù)組相關

    1.2 forEach(callback,context) 操作數(shù)組中的每一個元素

    ie9以上的瀏覽器,以及其他非IE瀏覽器都支持這一方法。

    以下是兼容性的擴展寫法:

    /**
        forEach除了接受一個必須的回調函數(shù)參數(shù),還可以接受一個可選的上下文參數(shù)(改變回調函數(shù)里面的this指向)(第2個參數(shù))。
    */
    if (!Array.prototype.forEach && typeof Array.prototype.forEach !== "function") {
        Array.prototype.forEach = function(callback, context) {
           // 遍歷數(shù)組,在每一項上調用回調函數(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 = ['雪碧','可樂','脈動','紅牛','農夫山泉'];
            
    var context = {
        str1 : '【',
        str2 : '】'
    };
            
    drinks.forEach(function(item){
        console.log(this.str1 + item + this.str2);
    },context);

    效果:

    JavaScript常用方法和封裝實例分析

    這個方法在各大瀏覽器都得到了較好的支持。

    1.3 indexOf(searchvalue,fromindex) 查詢數(shù)組中某一個值的下標

    ie9以上的瀏覽器,以及其他非IE瀏覽器都支持這一方法。

    以下是兼容性的擴展寫法:

    //獲取某元素在數(shù)組中第一次出現(xiàn)的下標
    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)的下標
    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ù)組的構造器是咋樣的?
    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

    雖然取巧了點,不過目的確實達到了。

    2.數(shù)組封裝

    通過數(shù)組的一些基本方法,我們可以開始自己模擬一下java中的ArrayList

    代碼如下:

    //模擬ArrayList
    function ArrayList(){
        var arr = []; //用于保存數(shù)據(jù)的數(shù)組
        var length = 0; //數(shù)組的長度,默認為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: 是否全部刪除,否則默認刪除第一個匹配項
        */
       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ù)索引獲取對應的元素
        */
       this.get = function(index){
        if(index > length - 1){
            return null;
        }
        return arr[index];
       }
       
       /**
        * 獲取列表數(shù)組
        */
       this.toArray = function(){
         return arr;
       }
       
       /**
        * 獲取某一個元素的角標
        * 如果只出現(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('趙六'));

    運行結果:

    JavaScript常用方法和封裝實例分析

    關于“JavaScript常用方法和封裝實例分析”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“JavaScript常用方法和封裝實例分析”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道。

    向AI問一下細節(jié)

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

    AI