JS 數組轉對象 對象轉數組 對象數組互相轉換 數組對象互相轉換


  • JS 數組轉對象 對象轉數組  對象數組互相轉換  數組對象互相轉換
  • 聲明一個函數,arr_obj ,里面接收一個參數,參數類型只接受對象或者數組

  • 如果沒有傳遞任何參數  或者 傳遞的參數類型不符合要求,就會拋出錯誤異常

  • 無論是沒有傳遞任何參數 或者 傳遞的參數類型不符合要求,拋出異常 並 打印出傳遞的參數

  • 如果要查看當前函數的對象,請通過 new 的方式實例化函數 arr_obj ,自行在控制台打印輸出

  • 調用此函數,傳入數組會自動轉換為對象;傳入對象會自動轉換為數組

  • 針對嵌套深層次比較深的對象或者數組

    // 數組轉對象、對象轉數組
    function arr_obj(query) {
      // 如果未傳遞參數,就賦值為 undefined
      this.query = query || undefined;
      this.params = this.query;
    
      // 默認對象
      var defaultObj = {};
      // 默認數組
      var defaultArr = [];
      // 數組轉對象
      this.arrToObj = function(arr) {
        var obj = {}
        for (var i = 0; i < arr.length; i++) {
          // 數組轉為對象,對象的鍵=數組值, 對象的值=數組值
          obj[arr[i]] = arr[i];
          // 如果是數組,就再次調用自身 (this.arrToObj),遞歸接着循環
          if (Object.prototype.toString.call(arr[i]) == "[object Array]") {
            var deepArray = this.arrToObj(arr[i])
            continue;
          } else {
            defaultObj[arr[i]] = arr[i]
          }
        }
        this.params = defaultObj;
      };
    
      // 對象轉數組
      this.objToArr = function(obj) {
        var arr = [];
        for (var i in obj) {
          arr.push(obj[i]);
          // 如果是對象,就再次調用自身 (this.ObjToObj),遞歸接着循環
          if(Object.prototype.toString.call(obj[i]) == "[object Object]"){
            var deepObject=this.objToArr(obj[i]);
            continue;
          }else{
            defaultArr.push(obj[i])
          }
        }
        this.params = defaultArr;
      };
    
      if (Object.prototype.toString.call(this.query) == "[object Array]") {
        this.arrToObj(this.query);
      } else if (Object.prototype.toString.call(this.query) == "[object Object]") {
        this.objToArr(this.query);
      } else if (Object.prototype.toString.call(this.query) == "[object Undefined]") {
        console.error("沒有獲取到傳遞進來的參數", this.params);
        throw "沒有獲取到傳遞進來的參數"
      } else {
        console.error("錯誤的參數:", this.params,
          "錯誤的參數類型:", Object.prototype.toString.call(this.params));
        throw "傳遞的參數只能是對象或者數組類型"
      }
      return this.params;
    }
    // 調用 對象轉數組
    var obj = {
      a1:"a",
      b1:{
        c1:"c",d1:"d"
        ,q1:{
          q:"q",w:"w",
        },
      },
      e1:"e",
      f1:"f"
      };
    // // 調用 數組轉對象
    var arr = ["a", ["c",["e"],"q"],"t"];
    var asd1 = new arr_obj(arr);
    console.log(asd1);
    // 輸出 {a: "a", c: "c", e: "e", q: "q", t: "t"}
    // 調用 對象轉數組
    var asd2=new arr_obj(obj);
    console.log(asd2);
    // 輸出  ["a", "c", "d", "q", "w", "e", "f"]

    可訪問此處進入原文 https://mp.weixin.qq.com/s/Ged8ZbUGy14qwPf7pcjCLQ


  • 免責聲明!

    本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



     
    粵ICP備18138465號   © 2018-2025 CODEPRJ.COM