Skip to content Skip to sidebar Skip to footer

Javascript Alternatives

In some projects that I work, was added some blocks with this syntax: var [code, name] = input.split('/'); console.log(code); console.log(name); I really like this, is so simple a

Solution 1:

See:

Possible to assign to multiple variables from an array?

for a similar discussion - unfortunately no cross browser solution seems to exist at the moment - safer to use a temp variable

Solution 2:

It's not as nice as the code you proposed, but I think it looks pretty good nevertheless, although you do have to make some workarounds:

First of all, the idea is to make a clean syntax for calling this function, such as:

[5,4,3,2,1].list(a,b,c,d,e);

The idea is that a,b,c,d,e are modified by reference.

Since variables are passed as value and only objects are passed by reference, the variables a,b,c,d,e must be objects.

var a=Object(),b=Object(),c=Object(),d=Object(),e=Object();

Once they are objects, you are able to modify their value by reference (as explained here http://sirdarckcat.blogspot.com.ar/2007/07/passing-reference-to-javascript.html)

(function(val){if(val)this.valueOf=this.toSource=this.toString=function(){returnval};returnval;}).call(myVariable,'MyNewValue')

So, wrapping it up in a "list" function which extends the Array.prototype, I ended up with this:

        Array.prototype.list = function(){
            for(var i=0;i<this.length;i++){
                (function(val){if(val)this.valueOf=this.toSource=this.toString=function(){returnval};returnval;}).call(arguments[i],this[i])
            }
        }

So when you call [5,4,3,2,1].list(a,b,c,d,e); you are actually modifying objects by reference (and the result will be an object too).

Here's the full working code:

<!DOCTYPE html><html><head><title>test</title><scripttype="text/javascript">Array.prototype.list = function(){
                for(var i=0;i<this.length;i++){
                    (function(val){if(val)this.valueOf=this.toSource=this.toString=function(){return val};return val;}).call(arguments[i],this[i])
                }
            }
        </script></head><body><aid="test"href="#">test</a><scripttype="text/javascript">var a=Object(),b=Object(),c=Object(),d=Object(),e=Object();
            [5,4,3,2,1].list(a,b,c,d,e);
            console.log(a,b,c,d,e);
        </script></body></html>

Post a Comment for "Javascript Alternatives"