How to use destructuring assignment to define enumerations in ES6?

前端 未结 2 406
Happy的楠姐
Happy的楠姐 2021-01-11 12:43

You can use destructuring assignment to define enumerations in ES6 as follows:

var [red, green, blue] = [0, 1, 2];
         


        
2条回答
  •  独厮守ぢ
    2021-01-11 13:43

    Note, each of the below prospective approaches could probably be improved.

    The variables appear to be global at Question. You can create an array of strings referencing the variable which should be created, define the variable from the element of the array

    // not technically destructuring, though achieves same result;
    // that is, setting variables globally
    for (var prop of (props = ["a", "b", "c", "d"])) {
      // set identifier globally
      self[prop] = props.indexOf(prop); // set a value for each `prop`
    }
    // delete `prop`, `props`
    prop = props = void 0;
    
    console.log(a, b, c, d);

    Other approaches

    using object destructuring

    var {
      red, blue, green
    } = (function(data, props) {
          for (var prop of Object.keys(props)) {
            data[props[prop]] = props.indexOf(props[prop]); // or some other value
          };
          return data
        }({}, ["red", "blue", "green"]));
    
    console.log(red, blue, green);

    using a list of variables to be

    var props = ["red", "blue", "green"]; // list of variables to be
    var [red, blue, green] = props.map((v, k) => k);
    console.log(red, blue, green, "window[\"red\"]:", window[props[0]]);

提交回复
热议问题