xinggevip

Es2015 json的简写、Object的is()、assign()、keys(), values(), entries()的方法、三个点解构对象
index.html<!DOCTYPE html> <html lang="en&qu...
扫描右侧二维码阅读全文
12
2019/06

Es2015 json的简写、Object的is()、assign()、keys(), values(), entries()的方法、三个点解构对象

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    
    <script>
        // json的简写方式
        let name = 'tom';
        let age = 18;
        let json = {
            name, // name:name,
            age, // age:age
            /*
            show:function (){
                return this.name;
            }
            */
            show(){
                return this.name;
            }
        };
        console.log(json); // {name: "tom", age: 18}
        console.log(json.show()); //tom
        
        // Obiect.is 比较来两个值是否相等
        console.log(NaN == NaN); //false
        console.log(Object.is(NaN,NaN)); //true
        console.log(+0 == -0); //true
        console.log(Object.is(+0,-0)); //false
        // Object.assign 用来合并对象的
        // Object.assign  合并对象
        let json1 = {a:1};
        let json2 = {b:2};
        let json3 = {c:3};
        let newjson = Object.assign({},json1,json2,json3); // {a: 1, b: 2, c: 3}
        console.log(newjson);
        // Object.assign 可以赋值数组
        let arr1 = [1,2,3];
        let newarr = Object.assign([],arr1);
        console.log(newarr);
        // Object.keys 循环字段
        // Object有keys, values, entries三个处理循环的方法
        let json4 = {
            name:'tom',
            age:18,
            sex:'男'
        };
        for(let key of Object.keys(json4)){
            console.log(key); // name age sex
        };
        
        // 对Object对象进行解构
        let {keys, values, entries} = Object;
        for(let key of keys(json4)){
            console.log(key); // name age sex
        };
        for(let key of values(json4)){
            console.log(key); // tom 18 男
        };
        for(let key of entries(json4)){
            console.log(key); 
            // (2) ["name", "tom"]
            // (2) ["age", 18]
            // (2) ["sex", "男"]
        };
        for(let [key,val] of entries(json4)){
            console.log(key,val);
            // name tom
            // age 18
            // sex 男
        };
        // 三个点解构对象
        let {x,y,...z} = {x:"apple",y:"banana",c:"orange",d:1,e:2};
        console.log(x,y,z); // apple banana {c: "orange", d: 1, e: 2}
        // 快速复制一个对象
        let json5 = {
            a:1,
            b:2
        };
        let newjson5 = {...json5};
        console.log(newjson5);  // {a: 1, b: 2}
    </script>
</body>
</html>
Last modification:June 12th, 2019 at 11:26 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment