欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ES6对象优化

程序员文章站 2022-07-13 09:33:21
...

一 点睛

扩展运算符( spread )是三个点(...)。它将一个数组或对象转为用逗号分隔的参数序列。

二 实战

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /* 对象的新方法 */
        const person = {
            name: "jack",
            age: 21,
            language: ['java', 'js', 'css']
        }
        //key/values/entries方法
        console.log(Object.keys(person)); // ["name", "age", "language"]
        console.log(Object.values(person)); // ["jack", 21, Array(3)]
        console.log(Object.entries(person)); // [Array(2), Array(2), Array(2)]

        const target = { a: 1 };
        const source1 = { b: 2 };
        const source2 = { c: 3 };

        // assign将源对象的所有可枚举属性复制到目标对象中。
        Object.assign(target, source1, source2);
        console.log(target); // {a:1,b:2,c:3}

        /* 声明对象简写 */
        const age = 23
        const name = "张三"
        //原本声明对象
        const person1 = { age: age, name: name }

        //简写后(若属性名与常量名相同时才可以使用)
        const person2 = { age, name }
        console.log(person2);

        /* 对象函数属性简写 */
        let person3 = {
            name: "jack",
            // 以前:
            eat: function (food) {
                console.log(this.name + "在吃" + food);
            },
            //箭头函数this不能使用,对象.属性
            eat2: food => console.log(person3.name + "在吃" + food),
            eat3(food) {
                console.log(this.name + "在吃" + food);
            }
        }

        person3.eat("苹果")
        person3.eat("香蕉")
        person3.eat("梨子")

        /* 对象扩展运算符 */
        // 1 拷贝对象(深拷贝)
        let p1 = { name: "Amy", age: 15 }
        let someone = { ...p1 }
        console.log(someone)  // {name: "Amy", age: 15}

        // 2 合并对象
        let age1 = { age: 15 }
        let name1 = { name: "Amy" }
        let p2 = { name: "zhangsan" }
        p2 = { ...age1, ...name1 }
        console.log(p2) // {age: 15, name: "Amy"}
    </script>
</body>

</html>

三 测试

ES6对象优化