Javascript. Assign array values to multiple variables? [duplicate] Javascript. Assign array values to multiple variables? [duplicate] arrays arrays

Javascript. Assign array values to multiple variables? [duplicate]


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.

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.

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

  • FireFox 2.0+
  • IE 9
  • Opera 11.50.

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

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


It is possible only for Javascript 1.7 as already answered by @Justin. Here is a trial to simulate it in the widespread browsers:

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

I don't know how useful it is.