JavaScript variable assignments from tuples

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

提交回复
热议问题