Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to assign to multiple variables from an array?

Tags:

javascript

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

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

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

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

like image 885
gregers Avatar asked May 25 '09 14:05

gregers


People also ask

Can you assign multiple variables at once?

You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables. It is also possible to assign to different types. If there is one variable on the left side, it is assigned as a tuple.

Can array store multiple variables?

An array in Java is used to store multiple values in a single variable, instead of declaring separate variables for each value. Therefore, an array is a collection of fixed elements in what can be seen as a list.

Can you assign a variable to an array?

An associative array variable can also be assigned an associative array variable value of the same associative array data type. This can be done using the assignment statement.


1 Answers

Destructuring assignment was standardized in ECMAScript 2015 (a.k.a. ES6). But not all browsers have implemented destructuring yet (as of March 2016), and even when they do it will take a while before users update to a browser with support. See examples in the spec for all the awesome things you can do. Here are some:

// Assign from array elements var [key, value] = "key:value".split(":"); // key => 'key' // value => 'value'  // Assign from object properties var {name: a, age: b} = {name: 'Peter', age: 5}; // a => 'Peter' // b => 5  // Swap [a, b] = [b, a] // a => 5 // b => 'Peter' 

Because this feature breaks backwards compatibility, you'll need to transpile the code to make it work in all browsers. Many of the existing transpilers support destructuring. Babel is a very popular transpiler. See Kangax´s table of browser and transpiler ES6-support.

More info:

Compatibility table for ES6 browser support

Exploring ES6 - Destructuring chapter

like image 137
gregers Avatar answered Sep 22 '22 10:09

gregers