JavaScript variable assignments from tuples

前端 未结 13 1338
[愿得一人]
[愿得一人] 2020-12-04 18:26

In other languages like Python 2 and Python 3, you can define and assign values to a tuple variable, and retrieve their values like this:

tuple = (\"Bob\", 2         


        
13条回答
  •  攒了一身酷
    2020-12-04 19:20

    Tuples aren't supported in JavaScript

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

    The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object is made effectively immutable. The method returns the object being frozen.

    Source: Mozilla Developer Network - Object.freeze()

    Assign an array as usual but lock it using 'Object.freeze()

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

    Use the values as you would a regular array (python multi-assignment is not supported)

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

    Attempt to assign a new value

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

    But the value is not changed

    > console.log(tuple)
    [ 'Bob', 24 ]
    

提交回复
热议问题