js基礎手寫Demo知識點總結

      /*
       * 知識點1: 變量聲明提升,但是賦值不不會提升
       */
       var a = 1;
       if(true) {
         console.log(a); // 1
         var a = 2;
         var b = 3;
       }
       console.log(a); //2
       console.log(b);  // 3
       b = 4; 
      

       /*
         * 知識點2: 同一標識符的前提下, 聲明都會提升,且函數聲明會覆蓋變量聲明。 但是初始化或賦值時,變量優先級高於函數。
       */
       console.log(a) // a(){}
       var a = 1;
       function a(){};
       console.log(a) // 1
       
       
       /*
        * 知識點3: 函數的實參可以通過arguments對應索引來改變值, 函數外變量於函數形參同名時,不會影響形參內的賦值及原始值
        */
       var a = 1;
       function fun(a, b) {
         a = 2;
         arguments[0] = 3;  // a=3
         arguments[1] = 1;  // b =1
         return a + b; // 4
       }
       console.log(fun(0, 0)); // 4
       console.log(a) // 1
    
      
      /*
      知識點4: for 循環爲同步任務,setTimeout 爲異步任務。主任務知曉完成後纔會將異步任務隊列推入執行;
               for 循環完成後i 值爲5, 所以最後的console.log 輸出5
      */
      for(var i=0; i<5; i++) {
        setTimeout(function(){
          console.log("for i:", i)  // 輸出5個:   for i: 5
        }, 0)
      }
      console.log(i)  //5
      
      
      /*
      知識點5: 普通函數的繼承及實例化爲先實例化子類構造函數,後實例父類構造函數;
               函數內及原型上的變量,只能在實例化後可訪問,直接通過方法訪問報 error
               (先查找自己 構造函數,然後查找繼承對象的構造函數,然後查找繼承對象的原型鏈....  如果找到則停止後續查找)
       */
      function A() {
        this.num1 = 1;
      };
      A.prototype.num2 = 2;
      function B(){
        this.num1 = 3
      };
      B.prototype = new A();
      var b1 = new B();
      console.log(b1.num1);  // 3
      console.log(b1.num2); // 2
      var b2 = B();
      console.log(b2.num1); // error
      console.log(b2.num2); // error
      
      /*
       *   根據數組目錄樹集合,輸出樹對象
       */
       var data=[
        {id: 1, parentId: 0, name:'父節點1'},
        {id: 2, parentId: 1, name:'父節點1'},
        {id: 3, parentId: 1, name:'子節點11-1'},
        {id: 4, parentId: 2, name:'子節點12-1'},
        {id: 5, parentId: 3, name:'子節點11-2'},
      ];
      var parentIds = new Set(data.map(item=>item.id)) ;  // 自己寫一個獲取id集合的去重函數。 [0,1,2,3,4]
      function createTreeList (arry, newArry, parentId) {
        var tempAry = [];
        arry.forEach(function(item){
          if(item.parentId == parentId) {
            tempAry.push(item)
          }
        });
        if(!newArry.length) {
          newArry = tempAry;
        } else {
          newArry.forEach(function(item){
            if(item.children) {
              createTreeList(arry, item.children, item.parentId);
            }
            if(item.id == parentId) {
              item["children"] = tempAry
            }
          })
        }
        if(parentIds.length==0){
          return ;
        }
        createTreeList(arry, newArry, parentIds.splice(0,1)[0])
        return newArry;
      }
      var newArray = createTreeList(data, [], parentIds.splice(0,1)[0]);
      console.log('newTree:',newArray)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章