Reputation: 53
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.
Upvotes: 5
Views: 16969
Reputation: 435
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)
Upvotes: 0
Reputation: 39
There are no tuples in javascript. It returns the last evaluated value when a tuple is expressed in javascript.
const value = (1, 2, 3);
// value is three
I have no idea why it exists though.
Upvotes: 1
Reputation: 5735
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
Upvotes: 6
Reputation: 486
No Javascript doesn't have tuples so my advise will be to use an array of fixed size as a default tuple or maybe as an object which has the same properties as "named" tuples. Tuples are only created using arrays
Upvotes: 0
Reputation: 301
Sometimes it's just better to answer question directly without prolonging it with but you can but it can,
This should be more helpful for someone like me.
Does javascript have tuples type built in like ones in python?
Answer: No, tuples are not native types in javascript. Period.
Upvotes: -4
Reputation: 1157
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();
Upvotes: 8