简体   繁体   中英

Does JavaScript have tuples?

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.

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();

The closest to a tuple is using Object.seal() on an array which is initiated with the wanted length.

Otherwise, you can use a Proxy :

let tuple = [ 1, 0, 0 ];
tuple = new Proxy(tuple, {
    set(obj, prop, value) {
        if (prop > 2) {
            throw new RangeError('this tuple has a fixed length of three');
        }   
    }
});

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM