JavaScript中的解构赋值 [英] Destructuring assignment in JavaScript

查看:116
本文介绍了JavaScript中的解构赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Mozilla changlog for JavaScript 1.7中可以看出,他们已经添加了解构分配。可悲的是我不太喜欢语法(为什么要写a和b两次?):

As can be seen in the Mozilla changlog for JavaScript 1.7 they have added destructuring assignment. Sadly I'm not very fond of the syntax (why write a and b twice?):

var a, b;  
[a, b] = f();

这样的事情会好很多:

var [a, b] = f();

这仍然是向后兼容的。类似Python的解构不会向后兼容。

That would still be backwards compatible. Python-like destructuring would not be backwards compatible.

无论如何,我能想出的最好的JavaScript 1.5解决方案是:

Anyway the best solution for JavaScript 1.5 that I have been able to come up with is:

function assign(array, map) {
    var o = Object();
    var i = 0;
    $.each(map, function(e, _) {
        o[e] = array[i++];
    });
    return o;
}

其工作方式如下:

var array = [1,2];
var _ = assign[array, { var1: null, var2: null });
_.var1; // prints 1
_.var2; // prints 2

但这真的很糟糕,因为_没有任何意义。它只是一个存储名称的空壳。但遗憾的是它需要因为JavaScript没有指针。在正面,您可以在值不匹配的情况下指定默认值。另请注意,此解决方案不会尝试切片阵列。所以你不能做像 {first:0,rest:0} 这样的事情。但是,如果有人想要这种行为,这很容易就可以完成。

But this really sucks because _ has no meaning. It's just an empty shell to store the names. But sadly it's needed because JavaScript doesn't have pointers. On the plus side you can assign default values in the case the values are not matched. Also note that this solution doesn't try to slice the array. So you can't do something like {first: 0, rest: 0}. But that could easily be done, if one wanted that behavior.

什么是更好的解决方案?

What is a better solution?

推荐答案

首先, var [a,b] = f()在JavaScript 1.7中运行正常 - 试试吧!

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

其次,您可以使用使用来平滑使用语法

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

当然,这不允许你修改现有变量的值,所以恕我直言,它比JavaScript 1.7功能更有用。在代码中我正在编写现在,我只是直接返回对象并引用他们的成员 - 我将等待1.7功能变得更加广泛可用。

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.

这篇关于JavaScript中的解构赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆