可以从数组中分配多个变量吗? [英] Possible to assign to multiple variables from an array?

查看:168
本文介绍了可以从数组中分配多个变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是从JavaScript中的数组分配多个变量的标准方法吗?
在Firefox和Opera中,你可以这样做:

Is it a standard way to assign to multiple variables from an array in JavaScript? In Firefox and Opera, you can do:

var [key, value] = "key:value".split(":");
alert(key + "=" + value); // will alert "key = value";

但它在IE8或谷歌浏览器中不起作用。

But it doesn't work in IE8 or Google Chrome.

有没有人知道在没有tmp变量的情况下在其他浏览器中执行此操作的好方法?

Does anyone know a nice way to do this in other browsers without a tmp variable?

var tmp = "key:value".split(":");
var key=tmp[0], value=tmp[1];

这是即将推出的JavaScript版本,还是FF和Opera中的自定义实现?

Is this something that will come in an upcoming JavaScript version, or just custom implementation in FF and Opera?

推荐答案

如果您想知道将要发生什么,请阅读解构分配一节。

If you want to know what's coming, read the section on Destructuring Assignment.

https://developer.mozilla.org/en/New_in_javascript_1.7

您可以使用哪些语言功能始终取决于您的环境。

What language features you can use is always dependent on your environment.

为Mobile Safari开发(或例如,用于其他浏览器(如Palm Pre,Android等)或AIR的Web堆栈比为整个Web开发更加可预测(您甚至还需要考虑IE6)。

Developing for Mobile Safari (or a web stack for other browsers like the Palm Pre, Android, etc.) or AIR, for example, is more predictable than developing for the web at large (where you still have to take even IE6 into account).

针对当前问题的跨浏览器解决方案是初始化一个数组,其中包含要填充的变量列表.variable格式,然后循环。无法想象为什么你会这样做。似乎总会有更好的解决方案。

A cross-browser solution to the problem at hand would be to initialize an array that had a list of the variables you want to fill in window.variable format, then just loop through. Can't imagine why you'd do it though. Seems like there would always be a better solution.

这篇关于可以从数组中分配多个变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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