JavaScript variable assignments from tuples

前端 未结 13 1341
[愿得一人]
[愿得一人] 2020-12-04 18:26

In other languages like Python 2 and Python 3, you can define and assign values to a tuple variable, and retrieve their values like this:

tuple = (\"Bob\", 2         


        
13条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 19:07

    Here is a simple Javascript Tuple implementation:

    var Tuple = (function () {
       function Tuple(Item1, Item2) {
          var item1 = Item1;
          var item2 = Item2;
          Object.defineProperty(this, "Item1", {
              get: function() { return item1  }
          });
          Object.defineProperty(this, "Item2", {
              get: function() { return item2  }
          });
       }
       return Tuple;
    })();
    
    var tuple = new Tuple("Bob", 25); // Instantiation of a new Tuple
    var name = tuple.Item1; // Assignment. name will be "Bob"
    tuple.Item1 = "Kirk"; // Will not set it. It's immutable.
    

    This is a 2-tuple, however, you could modify my example to support 3,4,5,6 etc. tuples.

提交回复
热议问题