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

js的几个小技巧

程序员文章站 2022-03-10 22:01:33
...

1、解构原始数据

  const rawUser = {
       name: 'Allan',
       age: '25',
       sex: "man"
   };

   let user = {};
   ({ name: user.name, age: user.age} = rawUser);
   console.log(user);  // {name: "Allan", age: "25"}

2、动态增加属性

    const getUser = (emailIncluded) => {
        return {
            name: 'John',
            surname: 'Doe',
            ...emailIncluded && { email : '[email protected]' }
        }
    }

    const user = getUser(true);
    console.log(user); // outputs { name: "John", surname: "Doe", email: "[email protected]" }

    const userWithoutEmail = getUser(false);
    console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }

 

相关标签: JavaScript总结