ES6 export all values from object

前端 未结 9 1781
梦谈多话
梦谈多话 2020-11-28 07:32

Say I have a module (./my-module.js) that has an object which should be its return value:

let values = { a: 1, b: 2, c: 3 }

// \"export values\         


        
9条回答
  •  北海茫月
    2020-11-28 08:14

    I suggest the following, let's expect a module.js:

    const values = { a: 1, b: 2, c: 3 };
    
    export { values }; // you could use default, but I'm specific here
    

    and then you can do in an index.js:

    import { values } from "module";
    
    // directly access the object
    console.log(values.a); // 1
    
    // object destructuring
    const { a, b, c } = values; 
    console.log(a); // 1
    console.log(b); // 2
    console.log(c); // 3
    
    // selective object destructering with renaming
    const { a:k, c:m } = values;
    console.log(k); // 1
    console.log(m); // 3
    
    // selective object destructering with renaming and default value
    const { a:x, b:y, d:z = 0 } = values;
    console.log(x); // 1
    console.log(y); // 2
    console.log(z); // 0
    

    More examples of destructering objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

提交回复
热议问题