美文网首页
ES6之对象优化

ES6之对象优化

作者: YAOPRINCESS | 来源:发表于2020-07-11 16:00 被阅读0次
image.png

新增的API

  • keys():获取对象的所有key形成的数组
  • values():获取对象的所有value形成的数组
  • entries():获取key,value形成的二维数组
  • assign():合并多个对象
const person={
            name:"张三",
            age:11,
            language:['java','js','css']
        }
        console.log(Object.keys(person));
        console.log(Object.values(person));
        console.log(Object.entries(person));


        const target={a:1};
        const source1={b:2};
        const source2={c:3};
        console.log(Object.assign(target,source1,source2));

声明对象的简写方式

 //声明变量的简写
        const age=21;
        const name="张三";
        //以前
        const person1={age:age,name:name};
        console.log(person1);
        //现在(前提是变量名一样)
        const person2={age,name};
        console.log(person2);

对象的函数属性简写

对象拓展运算符

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        const person={
            name:"张三",
            age:11,
            language:['java','js','css']
        }
        console.log(Object.keys(person));
        console.log(Object.values(person));
        console.log(Object.entries(person));


        const target={a:1};
        const source1={b:2};
        const source2={c:3};
        console.log(Object.assign(target,source1,source2));


        //声明变量的简写
        const age=21;
        const name="张三";
        //以前
        const person1={age:age,name:name};
        console.log(person1);
        //现在(前提是变量名一样)
        const person2={age,name};
        console.log(person2);


        //函数属性简写
        //以前
        let person3={
            name:"jack",
            eat:function (food){
                console.log(this.name+"在吃"+food);
            },
            //箭头函数版,箭头函数是拿不到this的
            eat1:food=>console.log(person3.name+"在吃"+food),
            //简写版
            eat2(food){
                console.log(this.name+"在吃"+food);
            }
        }
        person3.eat("香蕉");
        person3.eat1("苹果");
        person3.eat2("桃子");


        //对象拓展运算符...,是深拷贝
        let p1={name:"jack",age:16};
        let p2={...p1};
        console.log(p2);

        let p3={name:"jack"};
        let p4={age:17};
        let p5={...p3,...p4};//如果属性重名取后面的
        console.log(p5);

    
    </script>
</body>
</html>

相关文章

网友评论

      本文标题:ES6之对象优化

      本文链接:https://www.haomeiwen.com/subject/wisicktx.html