I would love to know if there are python type tuples in JavaScript. I am working on a project and I need to just use a list of objects rather tan an array.
-
5No, it doesn't. You can use an array of fixed size as a generic tuple or an object with the same properties as "named" tuples.VLAZ– VLAZ2020-02-07 08:26:58 +00:00Commented Feb 7, 2020 at 8:26
-
2TypeScript maybe? typescriptlang.org/docs/handbook/basic-types.html#tuplewentjun– wentjun2020-02-07 08:29:30 +00:00Commented Feb 7, 2020 at 8:29
-
3Does this answer your question? JavaScript variable assignments from tuplesVLAZ– VLAZ2020-02-07 08:30:09 +00:00Commented Feb 7, 2020 at 8:30
-
so yes and no, because any array or object can work as tuple, but because of the loosly typed paradigm, you have to take care of your self.Nina Scholz– Nina Scholz2020-02-07 08:52:29 +00:00Commented Feb 7, 2020 at 8:52
-
You can use destructuring feature for tuple like behaviour developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Md. Khirul Islam Omi– Md. Khirul Islam Omi2020-02-07 08:53:33 +00:00Commented Feb 7, 2020 at 8:53
6 Answers
Javascript does not support a tuple data type, but arrays can be used like tuples, with the help of array destructuring. With it, the array can be used to return multiple values from a function. Do
function fun()
{
var x, y, z;
# Some code
return [x, y, z];
}
The function can be consumed as
[x, y, z] = fun();
But, it must be kept in mind that the returned value is order-dependent. So, if any value has to be ignored, then it must be destructured with empty variables as
[, , x, , y] = fun();
3 Comments
@typedef, or, you could include TypeScript definition files (.d.ts) and use TypeScript's Tuple type.The closest to a tuple is using Object.seal() on an array which is initiated with the wanted length:
let arr = new Array(1, 0, 0);
let tuple Object.seal(arr)
Otherwise, you can use a Proxy:
let arr = [ 1, 0, 0 ];
let tuple = new Proxy(tuple, {
set(obj, prop, value) {
if (prop > 2) {
throw new RangeError('this tuple has a fixed length of three');
}
}
});
Update: There is an ECMAScript proposal for a native implementation of a Tuple type
Comments
JavaScript does not have native tuples, but you could possibly roll your own. For example:
class Tuple extends Array {
constructor(...args) {
super();
this.push(...args);
Object.seal(this);
}
}
The tuple in this case is essentially just an array, but because it's sealed you cannot add or remove elements from it, so it will act like a tuple.
You can then create tuples like this:
let t = new Tuple(1,2)
2 Comments
(1, 'a') == (1, 'a') evaluates to True. But not with this solution.