ES學習筆記(11)--ES6中物件

weixin_34127717發表於2018-10-16

物件賦值

ES6允許把宣告的變數直接賦值給物件

        let name="jie";
        let skill = "web";
        var obj = {name,skill};
        console.log(obj)  //{name: "jie", skill: "web"}

物件Key值構建

        let key = 'skill';
        var obj = {
            [key]:'web'
        }
        console.log(obj.skill)  //web

自定義物件方法

物件方法就是把兌現中的屬性,用匿名函式的形式程式設計方法

        var obj = {
            add:function(a,b){
                return a+b;
            }
        }
        console.log(obj.add(1,2)) //3

Object.is( ) 物件比較

        var obj1 = {name:'jie'};
        var obj2 = {name:'jie'};
        console.log(obj1.name === obj2.name); //true
        console.log(Object.is(obj1.name,obj2.name)) //true

===為同值相等,is()為嚴格相等

        console.log(+0 === -0) //true
        console.log(NaN === NaN);  //false
        console.log(Object.is(+0,-0));  //false
        console.log(Object.is(NaN,NaN))  //true

Object.assign( )

合併物件

        var a = {a:'jie'};
        var b = {b:'biao'};
        var c = {c:"nine"};
        let d = Object.assign(a,b,c);
        console.log(d) //index.html:52 {a: "jie", b: "biao", c: "nine"}

物件的key重新賦值

如果物件的key已經存在,則重新賦值

        var a = {a:'jie'};
        var b = {b:'biao'};
        var c = {c:"nine"};
        let d = Object.assign(a,b,c);
        Object.assign(d,{
            c:"ninee"
        })
        console.log(d) //{a: "jie", b: "biao", c: "ninee"}

相關文章