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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With