的JavaScript。指定数组值多个变量? [英] Javascript. Assign array values to multiple variables?

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

问题描述

var a,b,c;
var arr = [1,2,3];
[a,b,c] = arr;

这code完美的作品在Firefox导致A = 1,B = 2,C = 3,结果
但它不能在Chrome中工作。它是Chrome错误或结果
它不是有效的JavaScript code? (我没能找到它在JavaScript参考)

this code works perfectly in Firefox resulting a=1, b=2 and c=3,
but it doesn't work in Chrome. Is it a Chrome bug or
it is not valid javascript code? (I failed to find it in javascript references)

我怎么能修改此code,使之适用于Chrome浏览器,用它伤害最小?结果
(我真的不喜欢写= ARR [0]; B =改编[1] ...或者arr.shift相同的()所有的时间)的

How can I modify this code to make it suitable for Chrome, with minimum damage to it?
(I don't really like to write a = arr[0]; b = arr[1]... or the same with arr.shift() all the time)

P.S。这只是一个例子code,在现实code结果
我得到的ARR数组从某处我的code外

P.S. this is just an example code, in real code
I get the arr array from somewhere outside my code

推荐答案

这是JavaScript 1.7中的新功能称为<一href=\"https://developer.mozilla.org/en/New_in_javascript_1.7#Destructuring_assignment_%28Merge_into_own_page.2Fsection%29\">Destructuring分配:

This is a new feature of JavaScript 1.7 called Destructuring assignment:

解构赋值使得可以使用镜像数组和对象字面建设语法提取数组或对象的数据。

Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

对象和数组文本前pressions提供了一种简单的方法来创建数据的临时包。一旦你创建的数据这些包,你可以用它们想要的任何方式。你甚至可以从函数返回他们。

The object and array literal expressions provide an easy way to create ad-hoc packages of data. Once you've created these packages of data, you can use them any way you want to. You can even return them from functions.

您可以用解构赋值做一个特别有用的事情是在一个单一的语句来读取整个结构,虽然也有一些有趣的事情,你可以与他们无关,如图充满例子节如下。

One particularly useful thing you can do with destructuring assignment is to read an entire structure in a single statement, although there are a number of interesting things you can do with them, as shown in the section full of examples that follows.

您可以用解构赋值,例如,交换值:

You can use destructuring assignment, for example, to swap values:

var a = 1;
var b = 3;
[a, b] = [b, a];

这个功能在语言如Perl和Python类似的功能present。

This capability is similar to features present in languages such as Perl and Python.

不幸的是,根据 时,JavaScript的1.7尚未在铬实现版本的该表格。但它应该是那里:

Unfortunately, according to this table of versions, JavaScript 1.7 has not been implemented in Chrome. But it should be there in:


  • 火狐2.0 +

  • IE 9

  • 歌剧11.50。

你可以尝试一下这个的jsfiddle: http://jsfiddle.net/uBReg/

Try it for yourself in this jsfiddle: http://jsfiddle.net/uBReg/

我测试在Chrome(失败),IE 8(失败),而Firefox 5(它的工作,每维基表)。

I tested this on Chrome (failed), IE 8 (failed), and FireFox 5 (which worked, per the wiki table).

这篇关于的JavaScript。指定数组值多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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