简体   繁体   English

JavaScript 有元组吗?

[英]Does JavaScript have tuples?

I would love to know if there are python type tuples in JavaScript.我很想知道 JavaScript 中是否有 python 类型的元组。 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. Javascript 不支持元组数据类型,但在数组解构的帮助下,数组可以像元组一样使用。 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.最接近元组的是在以所需长度启动的数组上使用Object.seal()

Otherwise, you can use a Proxy :否则,您可以使用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.没有 Javascript 没有元组,所以我的建议是使用一个固定大小的数组作为默认元组,或者作为一个 object ,它具有与“命名”元组相同的属性。 Tuples are only created using arrays元组仅使用 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? javascript 是否在 python 中内置了类似的元组类型?

Answer: No, tuples are not native types in javascript.答:不,元组不是 javascript 中的原生类型。 Period.时期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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