Possible to assign to multiple variables from an array?
Asked Answered
B

7

45

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?

Blondell answered 25/5, 2009 at 14:57 Comment(2)
Is splitting on the colon safe? What if there's a colon in one of the values?Yasukoyataghan
Hi, don't worry about the colon. It was a random example. I'm just wondering if it's possible to assign to multiple variables from an array. Or if it might be possible in the near future.Blondell
Y
9

If you want to know what's coming, read the section on Destructuring Assignment.

https://developer.mozilla.org/en/New_in_javascript_1.7

What language features you can use is always dependent on your environment.

Developing for Mobile Safari (or a web stack for other browsers like the Palm Pre, Android, etc.) or AIR, for example, is more predictable than developing for the web at large (where you still have to take even IE6 into account).


A cross-browser solution to the problem at hand would be to initialize an array that had a list of the variables you want to fill in window.variable format, then just loop through. Can't imagine why you'd do it though. Seems like there would always be a better solution.

Yasukoyataghan answered 25/5, 2009 at 17:41 Comment(1)
developer.mozilla.org/en/… was just what I was looking for! I tried reading the EcmaScript spec, but that was a bit heavy. The mozilla documentation was very good! Thanks :)Blondell
B
26

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

Blondell answered 3/3, 2014 at 14:22 Comment(0)
Y
9

If you want to know what's coming, read the section on Destructuring Assignment.

https://developer.mozilla.org/en/New_in_javascript_1.7

What language features you can use is always dependent on your environment.

Developing for Mobile Safari (or a web stack for other browsers like the Palm Pre, Android, etc.) or AIR, for example, is more predictable than developing for the web at large (where you still have to take even IE6 into account).


A cross-browser solution to the problem at hand would be to initialize an array that had a list of the variables you want to fill in window.variable format, then just loop through. Can't imagine why you'd do it though. Seems like there would always be a better solution.

Yasukoyataghan answered 25/5, 2009 at 17:41 Comment(1)
developer.mozilla.org/en/… was just what I was looking for! I tried reading the EcmaScript spec, but that was a bit heavy. The mozilla documentation was very good! Thanks :)Blondell
A
5

Use destructuring assignment, a feature of ES6:

var [x, y] = [1, 2];
console.log(x, y); // 1 2
Afterdeck answered 15/10, 2019 at 17:14 Comment(1)
Another good example might be: let sentence = 'Hello World'; let [hello, world] = sentence.split(' '); Similar to how it's used in Python.Ishmul
S
4

I just had exactly same question, and as an exercise for myself came up with the following:

var key, value;

(function(arr){
  key=arr[0]; 
  value=arr[1];
})("key:value".split(":"));

alert(key + "=" + value);

Looks ugly to me, I'd rather use temp var (technically, I'm using here a temp variable anyway).

Edit: chrome supports that now. As for IE8: do we still care about it?

Sulfonal answered 18/5, 2012 at 18:24 Comment(0)
U
1

I don't think this is possible in a cross browser way. The best that I know which might help in a few circumstances is this:

// we'll pretend you don't need the key.
var value = "key:value".split(":")[1];
Undamped answered 25/5, 2009 at 15:12 Comment(0)
T
0

I think it should be a part of the new spec., then again it's a long read... :p

key = "key:value".split(":")[0];
value = "key:value".split(":")[1];

Only alternative I can think off.

Thin answered 25/5, 2009 at 15:11 Comment(7)
That's not an alternative, gregers noted that possible solution in his question.Saskatoon
using the temporary variable is a much better option!Undamped
He noted, the possibility of doing so with a temporary variable, however in this method there is no need for one.Thin
And call split() twice? You think that's better?Saskatoon
I agree temporary variable is a better option, but the question was for an alternative, and that's the only one I can think of.Thin
@Daniel: I don't think I ever claimed it was better. But sure, if you have an alternative for him that doesn't use a temporary variable and is cross-browser please share. I followed his requirements and that's the only thing that fits. Obviously and hopefully people would save cycles to not call split twice.Thin
Hmm, maybe a bit better: var str = "key:value"; str = str.split(":") then do the assigning. No extra temporary variable needed, just the string variable which you'll already have.Thin
Z
0

I don't know how you are using this, but if I was able to determine my own format for the "key:value" string, I'd be tempted to use json to just eval the string into the necessary object:

var obj = eval("{'key':'key_str', 'value':'val_str'}");
alert(obj.key + "=" + ojb.value);  //alerts "key_str=value_str
Zionism answered 25/5, 2009 at 15:26 Comment(2)
Sorry about the confusing question, but I specifically want to assign to multiple variables from an array. The split function will return an array. Btw eval is evil ;)Blondell
Ah, I see. The split() was just for the question, to get an array for your example. And why is eval evil? It's not secure, but then neither is anything in javascript.Zionism

© 2022 - 2024 — McMap. All rights reserved.