2011-08-08 87 views
60
var a,b,c; 
var arr = [1,2,3]; 
[a,b,c] = arr; 

此代碼在Firefox中完美工作,導致a = 1,b = 2和c = 3,
但它在Chrome中不起作用。是Chrome bug還是
它是無效的JavaScript代碼? (我未能在JavaScript參考中找到它)Javascript。將數組值賦給多個變量?

如何修改此代碼以使其適用於Chrome,並且損壞程度最低?
(I真的不喜歡寫= ARR [0]; B = ARR [1] ...或與arr.shift()所有的時間相同)

P.S.這僅僅是一個示例代碼,在真正的代碼
我從外面我的代碼某處

+1

Chrome中會發生什麼?你得到什麼錯誤信息? –

+0

它給我的下列:的ReferenceError 參數:數組[0] 消息: 「 - 」 堆棧: 「 - 」 類型: 「invalid_lhs_in_assignment」 __proto__:錯誤 – tsds

+1

FWIW,http://www.jslint.com/說沒關係(修正了一些空白之後;雖然我不知道它會評估什麼),但http://jshint.com/說這是一個不好的任務。 – JAAulde

回答

64

這是JavaScript 1.7中的新功能,稱爲Destructuring assignment得到ARR數組:

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

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]; 

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

不幸的是,根據this table of versions, Chrome瀏覽器尚未實施JavaScript 1.7。但應該還有在:

  • 火狐2.0 +
  • IE 9
  • 歌劇11.50。

你可以嘗試一下在此的jsfiddle:http://jsfiddle.net/uBReg/

我測試了在Chrome(失敗),IE 8(失敗),而Firefox 5(其工作,每維基表)。

+0

在下一個版本中,解構(有可能)[作爲官方語言功能](http://wiki.ecmascript.org/doku.php?id=harmony:destructuring) ECMAScript,所以谷歌瀏覽器肯定會達到那裏,假設提案堅持。 – user113716

+1

這將是偉大的;在JavaScript 1.7+中有一些令人興奮的功能......不幸的是,由於這些瀏覽器不兼容,它們目前無法用於「真實世界」應用程序。 –

+0

好的。你認爲有比a = arr.shift()更緊湊和更清晰的方法嗎? – tsds

7

只有Javascript 1.7可能已被@Justin回答。下面是一個在廣泛的瀏覽器中模擬它的試驗:

function assign(arr, vars) { 
    var x = {}; 
    var num = Math.min(arr.length, vars.length); 
    for (var i = 0; i < num; ++i) { 
     x[vars[i]] = arr[i]; 
    } 
    return x; 
} 
var arr = [1, 2, 3]; 
var x = assign(arr, ['a', 'b', 'c']); 
var z = x.a + x.b + x.c; // z == 6 

我不知道它有多有用。