Destructuring assignment in JavaScript

╄→尐↘猪︶ㄣ 提交于 2019-11-26 17:50:58
Shog9

First off, var [a, b] = f() works just fine in JavaScript 1.7 - try it!

Second, you can smooth out the usage syntax slightly using with():

var array = [1,2];
with (assign(array, { var1: null, var2: null }))
{
   var1; // == 1
   var2; // == 2
}

Of course, this won't allow you to modify the values of existing variables, so IMHO it's a whole lot less useful than the JavaScript 1.7 feature. In code I'm writing now, I just return objects directly and reference their members - I'll wait for the 1.7 features to become more widely available.

You don't need the dummy "_" variable. You can directly create "global" variables by using the window object scope:

window["foo"] = "bar";
alert(foo); // Gives "bar"

Here are few more points:

  • I wouldn't name this function "assign" because that's too generic a term.
  • To more closely resemble JS 1.7 syntax, I'd make the function take the destination as the first argument and the source as the second argument.
  • Using an object literal to pass the destination variables is cool but can be confused with JS 1.7 destructuring where the destination is actually an object and not an array. I prefer just using a comma delimited list of variable names as a string.

Here's what I came up with:

function destructure(dest, src) {  
    dest = dest.split(",");  

    for (var i = 0; i < src.length; i++) {  
        window[dest[i]] = src[i];  
    }  
}  

var arr = [42, 66];  

destructure("var1,var2", arr); 

alert(var1); // Gives 42
alert(var2); // Gives 66

Here's what I did in PHPstorm 10:

File -> Settings -> Languages & Frameworks -> ...

... set JavaScript language version to e.g. JavaScript 1.8.5...

-> click Apply.

In standard JavaScript we get used to all kinds of ugliness, and emulating destructuring assignment using an intermediate variable is not too bad:

function divMod1(a, b) {
    return [ Math.floor(a / b), a % b ];
}

var _ = divMod1(11, 3);
var div = _[0];
var mod = _[1];
alert("(1) div=" + div + ", mod=" + mod );

However I think the following pattern is more idomatic:

function divMod2(a, b, callback) {
    callback(Math.floor(a / b), a % b);
}

divMod2(11, 3, function(div, mod) {
    alert("(2) div=" + div + ", mod=" + mod );
});

Note, that instead of returning the two results as an array, we pass them as arguments to a callback function.

(See code running at http://jsfiddle.net/vVQE3/ )

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!