Tuple JavaScript assignment variables

In other languages, such as Python 2 and Python 3, you can define and assign values ​​to a tuple variable and extract their values ​​as follows:

tuple = ("Bob", 24) name, age = tuple print(name) #name evaluates to Bob print(age) #age evaluates to 24 

Is there something similar in JavaScript? Or I just need to do it in an ugly way with an array:

 tuple = ["Bob", 24] name = tuple[0] //name Evaluates to Bob age = tuple[1] //age Evaluates to 24 

Is there a better way to simulate Python tuples in JavaScript 5?

+66
javascript destructuring tuples
Dec 22 2018-10-22
source share
12 answers

You have to make it ugly. If you really want something like this, you can check out CoffeeScript , which has this and many other features that make it look more like python (sorry that sounds like an ad, but I like it a lot.)

+45
Dec 22 '10 at 18:34
source share

Javascript 1.7 added a destructive task that allows you to do what you need.

 function getTuple(){ return ["Bob", 24]; } var [a, b] = getTuple(); // a === "bob" , b === 24 are both true 
+78
Dec 22 '10 at 19:44
source share

You can do something like this:

 var tuple = Object.freeze({ name:'Bob', age:14 }) 

then specify name and age as attributes

 tuple.name tuple.age 
+26
Feb 22 '13 at 13:49
source share

This tuple function is called destructuring in EcmaScript2015 and will soon be supported by modern browsers. So far, it only supports Firefox and Chrome .

But hey, you can use a translator.

The code will look as good as python:

 let tuple = ["Bob", 24] let [name, age] = tuple console.log(name) console.log(age) 
+19
Nov 06 '15 at 10:18
source share

Unfortunately, you cannot use this tuple assignment syntax in (ECMA | Java) Script.

EDIT: Someone related to Mozilla / JS 1.7 - this will not work with a cross browser, but if it is not required, answer.

+5
Dec 22 '10 at 18:32
source share

Tuples are not supported in JavaScript

If you are looking for an immutable list, Object.freeze () can be used to make the array immutable.

The Object.freeze () method freezes the object, i.e. prevents the addition of new properties; prevents deletion of existing properties; and prevents changes to existing properties or their enumeration, customizability, or writeability. Essentially, an object becomes effectively immutable. The method returns a frozen object.

Source: Mozilla Developer Network - Object.freeze ()

Assign the array as usual, but lock it using "Object.freeze ()

 > tuple = Object.freeze(['Bob', 24]); [ 'Bob', 24 ] 

Use values ​​just like a regular array (python multitasking is not supported)

 > name = tuple[0] 'Bob' > age = tuple[1] 24 

Attempt to assign a new value

 > tuple[0] = 'Steve' 'Steve' 

But the meaning does not change

 > console.log(tuple) [ 'Bob', 24 ] 
+5
Mar 11 '15 at
source share

This is not intended for actual use in real life, just an interesting exercise. See Why use a JavaScript eval function as a bad idea? for details.

This is the closest thing you can get without resorting to vendor-specific extensions:

 myArray = [1,2,3]; eval(set('a,b,c = myArray')); 

Auxiliary function:

 function set(code) { var vars=code.split('=')[0].trim().split(','); var array=code.split('=')[1].trim(); return 'var '+vars.map(function(x,i){return x+'='+array+'['+i+']'}).join(','); } 

Proof that it works in an arbitrary area:

 (function(){ myArray = [4,5,6]; eval(set('x,y,z = myArray')); console.log(y); // prints 5 })() 

eval not supported in Safari.

+3
Apr 24 '12 at 13:00
source share

As a minister's answer, you can do this with es2015:

 function Tuple(...args) { args.forEach((val, idx) => Object.defineProperty(this, "item"+idx, { get: () => val }) ) } var t = new Tuple("a", 123) console.log(t.item0) // "a" t.item0 = "b" console.log(t.item0) // "a" 

https://jsbin.com/fubaluwimo/edit?js,console

+3
Feb 09 '16 at 4:55
source share

Here is a simple implementation of Jupp; Tuple:

 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 immutable. 

This is a 2-tuple, however you can change my example to support 3,4,5,6, etc.

+1
Sep 26 '14 at 16:57
source share

Javascript can also be a tuple type. Just define it using higher order functions (the academic term is the encoding in the church):

 const Tuple = (...args) => { const Tuple = f => f(...args); return Object.freeze(Object.assign(Tuple, args)); }; const get1 = tx => tx((x, y) => x); const get2 = tx => tx((x, y) => y); const bimap = f => g => tx => tx((x, y) => Tuple(f(x), g(y))); const toArray = tx => tx((...args) => args); // aux functions const inc = x => x + 1; const toUpperCase = x => x.toUpperCase(); // mock data const pair = Tuple(1, "a"); // application console.assert(get1(pair) === 1); console.assert(get2(pair) === "a"); const {0:x, 1:y} = pair; console.log(x, y); // 1 a console.log(toArray(bimap(inc) (toUpperCase) (pair))); // [2, "A"] const map = new Map([Tuple(1, "a"), Tuple(2, "b")]); console.log(map.get(1), map.get(2)); // ab 

Note that Tuple not used as a regular constructor. The solution does not rely on the prototype system in general, but solely on functions of a higher order.

What are the advantages of tuples over Array , which are used as tuples? Church-encoded tuples are unchanged in design and thus prevent side effects caused by mutations. This helps to create more reliable applications. In addition, it is easier to talk about code that distinguishes Array as a collection type (for example, [a] ) and tuples as related data of different types (for example, (a, b) ).

+1
May 21 '17 at 15:30
source share
 [a, b, c] = [2, 'momo', 7] // b === 'momo', c ===7 ... 
0
Nov 10 '17 at
source share

A frozen array behaves the same way with the python root:

 const tuple = Object.freeze(["Bob", 24]); let [name, age]; = tuple console.debug(name); // "Bob" console.debug(age); // 24 

Think and define a class

 class Tuple extends Array { constructor(...items) { super(...items); Object.freeze(this); } } let tuple = new Tuple("Jim", 35); let [name, age] = tuple; console.debug(name); // Jim console.debug(age); // 35 tuple = ["Bob", 24]; // no effect console.debug(name); // Jim console.debug(age); // 25 

It works today in all the latest browsers.

0
Nov 25 '17 at 14:16
source share



All Articles