es6学习笔记

1:数组的复制

let aa = [1,2,3];
let bb =aa;
let cc = [...aa];
console.log(bb);      //[1, 2, 3]
console.log(cc);      //[1, 2, 3]
aa[0]=4;
console.log(bb);      //[4, 2, 3]
console.log(cc);      //[1, 2, 3]

因为数组的复制,只是引用地址的复制,原数组aa发生变化,直接复制的bb数组也跟着变化,使用...深度克隆数组,这样改变aa数组之后 cc数组不会变化!

2:数组的合并:

        let aa =[1,2,3];
        let bb =[4,5,6];
        let cc =[...aa,...bb];
        let dd = aa.concat(bb);
        console.log(cc); //[1, 2, 3, 4, 5, 6]
        bb[0]=8;
        console.log(cc); //[1, 2, 3, 4, 5, 6]
        console.log(dd); //[1, 2, 3, 4, 5, 6]

es5使用concat函数,es6直接使用。。。

3:数组的赋值:

        let aa =[1,2,3];
        let bb =[4,5,6];
        let cc =[...aa,...bb];
        let [d,...rest]=cc;
        console.log(d);//1
        console.log(rest);//[2, 3, 4, 5, 6]
        bb[2]=7;
        console.log(rest);//[2, 3, 4, 5, 6]

。。。rest保存剩下的数组,且是深度赋值,修改原数组aa,不影响rest

 

4:对象的复制:

 1        let aa ={
 2             name:'haha'
 3         };
 4         let bb ={
 5             age:'11',
 6             name:'change'
 7         };
 8         let cc ={};
 9         Object.assign(cc,aa,bb);
10         console.log(cc);//{name: "change", age: "11"}Object.assign(目标对象,原对象1,原对象2)


值得注意的是:

数组嵌套数组的数据格式,无法简单的用concat等方法达到深复制的目的:

比如:

var ceshiData = [
            [
                {
                    name:'huahua',
                    age:'11'
                },
                {
                    name:'xiaoming',
                    age:'20'
                }
            ]  
]

无法用下面的方法完成深复制的目的:

var aa = [];
aa= ceshiData.concat();
aa[0].push({
       name:'lili',
       age:'33'
 });
console.log(ceshiData);

这样还是会引用复制的!!

posted @ 2017-12-19 18:03  小猪冒泡  阅读(123)  评论(0编辑  收藏  举报