1. 程式人生 > >es6——內建物件擴充套件 陣列擴充套件(Array.form和Array.of) 物件的擴充套件

es6——內建物件擴充套件 陣列擴充套件(Array.form和Array.of) 物件的擴充套件

1.內建物件擴充套件

顯示一行 不方便觀看

     {
            let html='<body>' +
                '<p>good luck</p>' +
                '</body>';

            console.log(html);//<body><p>good luck</p></body>
        }

模板字串 (好處:1.方便觀看 2.內容方便改寫)

     {
            let str='hello world';
            let className='text';

            let html=`<body
>
<p>good luck</p> <p class="${className}">${str}</p> <p class="cc">${str}</p> </body>`;//可以外接修改class; console.log(html); /* <body
>
<p>good luck</p> <p class="text">hello world</p> <p class="cc">hello world</p> </body> */ }

2.陣列擴充套件

Array.from(偽陣列轉換真陣列)

       {
            let allLis=document.querySelectorAll('li'
); console.log(allLis);//NodeList(6) [li, li, li, li, li, li] console.log(Array.isArray(allLis));//false 偽陣列 let newLis=Array.from(allLis); console.log(newLis);//(6) [li, li, li, li, li, li] console.log(Array.isArray(newLis));//true 陣列 }

Array.of

     {
            console.log(Array.of(1, 2, 3, 4));//(4) [1, 2, 3, 4]
            console.log(Array.of('bob', 'lucy', 'tom'));//(3) ["bob", "lucy", "tom"]
        }

3.物件的擴充套件

key 和 value是一樣的,寫一個就夠了

      {
            let name='bob';
            let age=20;
            let obj={
                name,
                age
            };
            console.log(obj);//{name: "bob", age: 20}
        }

Object.assign() (合併物件)

     {
            let obj1={'name':'lucy'};
            let obj2={'age':20};
            let obj3={'sex':'man'};
            let obj4={'friends':'bob'};
            let obj={};
            Object.assign(obj,obj1,obj2,obj3,obj4);
            console.log(obj);//{name: "lucy", age: 20, sex: "man", friends: "bob"}
        }

延展操作符(拆解作用)

        {
            let str='hello world';
            let strAll=[...str];
            console.log(strAll);//(11) ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
        }
        {
            let student={
                name:'lucy',
                age:20,
                sex:'women'
            };
            //1.高效傳遞資料
            console.log({...student});//{name: "lucy", age: 20, sex: "women"}
            //2.去除重複元素
            let myArr=[1,2,3,2,3,'234',56,2];
            console.log(new Set(myArr));//偽陣列:Set(5) {1, 2, 3, "234", 56}
            console.log([...new Set(myArr)]);//陣列:(5) [1, 2, 3, "234", 56]
        }