js senior study notes (c)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/litcangosh/article/details/100747082
  • Shallow vs. deep copy
  1. Shallow copy: is to copy the contents of one object to another object copy, or a copy of the object to another address in the address of an object, they point to the same, they have the same properties and methods directly, are can use.
  2. Deep copy: the object of all properties and methods, one by one to find. And a corresponding open space on another object, and then stored one by one to another object.
 //浅拷贝
    // var obj1={
    //     age:20,
    //     name:"小明",
    //     car:["大众","捷达","奥迪"],
    //     dog:{
    //         sex:"男",
    //         color:"green"
    //     }
    // };
    // var obj2={};
    // for (var key in obj1){
    //     obj2[key]=obj1[key];
    // }
    // console.log(obj1);
    // console.log(obj2.car);

    //深拷贝
    var obj1 = {
        age: 20,
        name: "小明",
        car: ["大众", "捷达", "奥迪"],
        dog: {
            sex: "男",
            color: "green"
        }
    };
    var obj2 = {};

    function extend(a, b) {
        for (var key in a) {
            var item = a[key];
            //如果属性值是数组
            if (item instanceof Array) {
                b[key] = [];//在b中添加一个属性,属性值也是数组
                extend(item, b[key]);
                //如果属性值里面是对象
            } else if (item instanceof Object) {
                b[key] = {};//在b中添加一个属性,属性值是对象
                extend(item, b[key]);
            } else {
                b[key] = a[key];
            }
        }
    }
    extend(obj1, obj2);
    console.log(obj1);
    console.log(obj2);

 

  • Traversing the DOM tree
//获取页面的根节点
    //根据根节点,调用fn的函数,显示的是根节点的名字
    var root=document.documentElement;
    //循环遍历DOM树
    function forDom(root1) {
        //获取根节点下的所有子节点
        var children=root1.children;
        //调用遍历所有子节点的函数
        forChildren(children);
    }
    //给我所有的子节点,我把这个子节点中的所有的子节点显示出来
    function forChildren(children) {
        for (var i=0;i<children.length;i++){
            var child=children[i];
            f1(child);//显示节点名字
            //判断child下面有没有子节点,如果还有子节点,那么就继续的遍历
            child.children&&forDom(child);//递归
        }

    }
    forDom(root);
    //显示节点名字
    function f1(node) {
        console.log("节点的名字:"+node.nodeName);
    }

 

Guess you like

Origin blog.csdn.net/litcangosh/article/details/100747082