Structs in Javascript

后端 未结 8 1423
花落未央
花落未央 2020-12-12 09:29

Previously, when I needed to store a number of related variables, I\'d create a class.

function Item(id, speaker, country) {
    this.id = id;
    this.speak         


        
8条回答
  •  被撕碎了的回忆
    2020-12-12 09:47

    Following Markus's answer, in newer versions of JS (ES6 I think) you can create a 'struct' factory more simply using Arrow Functions and Rest Parameter like so:

    const Struct = (...keys) => ((...v) => keys.reduce((o, k, i) => {o[k] = v[i]; return o} , {}))
    const Item = Struct('id', 'speaker', 'country')
    var myItems = [
        Item(1, 'john', 'au'),
        Item(2, 'mary', 'us')
    ];
    
    console.log(myItems);
    console.log(myItems[0].id);
    console.log(myItems[0].speaker);
    console.log(myItems[0].country);
    

    The result of running this is:

    [ { id: 1, speaker: 'john', country: 'au' },
      { id: 2, speaker: 'mary', country: 'us' } ]
    1
    john
    au
    

    You can make it look similar to Python's namedtuple:

    const NamedStruct = (name, ...keys) => ((...v) => keys.reduce((o, k, i) => {o[k] = v[i]; return o} , {_name: name}))
    const Item = NamedStruct('Item', 'id', 'speaker', 'country')
    var myItems = [
        Item(1, 'john', 'au'),
        Item(2, 'mary', 'us')
    ];
    
    console.log(myItems);
    console.log(myItems[0].id);
    console.log(myItems[0].speaker);
    console.log(myItems[0].country);
    

    And the results:

    [ { _name: 'Item', id: 1, speaker: 'john', country: 'au' },
      { _name: 'Item', id: 2, speaker: 'mary', country: 'us' } ]
    1
    john
    au
    

提交回复
热议问题