JavaScript variable assignments from tuples

前端 未结 13 1231
[愿得一人]
[愿得一人] 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:03

    This "tuple" feature it is called destructuring in EcmaScript2015 and is soon to be supported by up to date browsers. For the time being, only Firefox and Chrome support it.

    But hey, you can use a transpiler.

    The code would look as nice as python:

    let tuple = ["Bob", 24]
    let [name, age] = tuple
    
    console.log(name)
    console.log(age)
    
    0 讨论(0)
  • 2020-12-04 19:04

    This is not intended to be actually used in real life, just an interesting exercise. See Why is using the JavaScript eval function a bad idea? for details.

    This is the closest you can get without resorting to vendor-specific extensions:

    myArray = [1,2,3];
    eval(set('a,b,c = myArray'));
    

    Helper function:

    function set(code) {
        var vars=code.split('=')[0].trim().split(',');
        var array=code.split('=')[1].trim();
        return 'var '+vars.map(function(x,i){return x+'='+array+'['+i+']'}).join(',');
    }
    

    Proof that it works in arbitrary scope:

    (function(){
        myArray = [4,5,6];
        eval(set('x,y,z = myArray'));
        console.log(y);  // prints 5
    })()
    

    eval is not supported in Safari.

    0 讨论(0)
  • 2020-12-04 19:04

    Here is a version of Matthew James Davis's answer with the Python tuple methods added in:

    class Tuple extends Array { 
      constructor(...items) { 
        super(...items); 
        Object.freeze(this);
      }
      toArray() {
        return [...this];
      }
      toString() {
        return '('+super.toString()+')';
      }
      count(item) {
        var arr = this.toArray();
        var result = 0;
        for(var i = 0; i < arr.length; i++) {
           if(arr[i] === item) {
             result++;
           }
        }
        return result;
      }
    
      
    
      
    }
    
       let tuple = new Tuple("Jim", 35);
       let [name,age] = tuple;
    
    console.log("tuple:"+tuple)
    console.log("name:"+name)
    console.log("age:"+age)

    0 讨论(0)
  • 2020-12-04 19:05

    Javascript 1.7 added destructured assignment which allows you to do essentially what you are after.

    function getTuple(){
       return ["Bob", 24];
    }
    var [a, b] = getTuple();
    // a === "bob" , b === 24 are both true
    
    0 讨论(0)
  • 2020-12-04 19:05

    I made a tuple implementation that works quite well. This solution allows for array destructuring, as well as basic type-cheking.

    const Tuple = (function() {
        function Tuple() {
            // Tuple needs at least one element
            if (arguments.length < 1) {
                throw new Error('Tuple needs at least one element');
            }
    
            const args = { ...arguments };
    
            // Define a length property (equal to the number of arguments provided)
            Object.defineProperty(this, 'length', {
                value: arguments.length,
                writable: false
            });
    
            // Assign values to enumerable properties
            for (let i in args) {
                Object.defineProperty(this, i, {
                    enumerable: true,
                    get() {
                        return args[+i];
                    },
                    // Checking if the type of the provided value matches that of the existing value
                    set(value) {
                        if (typeof value !== typeof args[+i]) {
                            throw new Error('Cannot assign ' + typeof value + ' on ' + typeof args[+i]);
                        }
    
                        args[+i] = value;
                    }
                });
            }
    
            // Implementing iteration with Symbol.iterator (allows for array destructuring as well for...of loops)
            this[Symbol.iterator] = function() {
                const tuple = this;
    
                return {
                    current: 0,
                    last: tuple.length - 1,
                    next() {
                        if (this.current <= this.last) {
                            let val = { done: false, value: tuple[this.current] };
                            this.current++;
                            return val;
                        } else {
                            return { done: true };
                        }
                    }
                };
            };
    
            // Sealing the object to make sure no more values can be added to tuple
            Object.seal(this);
        }
    
        // check if provided object is a tuple
        Tuple.isTuple = function(obj) {
            return obj instanceof Tuple;
        };
    
        // Misc. for making the tuple more readable when printing to the console
        Tuple.prototype.toString = function() {
            const copyThis = { ...this };
            const values = Object.values(copyThis);
            return `(${values.join(', ')})`;
        };
    
        // conctat two instances of Tuple
        Tuple.concat = function(obj1, obj2) {
            if (!Tuple.isTuple(obj1) || !Tuple.isTuple(obj2)) {
                throw new Error('Cannot concat Tuple with ' + typeof (obj1 || obj2));
            }
    
            const obj1Copy = { ...obj1 };
            const obj2Copy = { ...obj2 };
    
            const obj1Items = Object.values(obj1Copy);
            const obj2Items = Object.values(obj2Copy);
    
            return new Tuple(...obj1Items, ...obj2Items);
        };
    
        return Tuple;
    })();
    
    const SNAKE_COLOR = new Tuple(0, 220, 10);
    
    const [red, green, blue] = SNAKE_COLOR;
    console.log(green); // => 220
    
    
    
    0 讨论(0)
  • 2020-12-04 19:07

    You can do something similar:

    var tuple = Object.freeze({ name:'Bob', age:14 })
    

    and then refer to name and age as attributes

    tuple.name 
    tuple.age 
    
    0 讨论(0)
提交回复
热议问题