views:

88

answers:

5

This is a simple problem, and I've done it before. I just can't remember how, or what exactly it was called.

In python I can do this:

arr = ['one', 'two']
one, two = arr

how do I do that in JavaScript?

+3  A: 

That's destructuring assignment. You can do it in some browsers with the following syntax:

[one, two] = arr;

It's not supported by Internet Explorer though. This was a feature introduced with ECMAScript 4 which is now ECMAScript Harmony, so we might see it in a future revision of the specification.

Andy E
+2  A: 
var one = arr[0];
var two = arr[1];
rob waminal
aw c'mon, that's no fun at all
Carson Myers
You should really use `var` to prevent the variables from polluting the global scope.
Mathias Bynens
I'm just assuming its all declared variables :)
rob waminal
well, i don't know, depends on the coder :)
rob waminal
It’s probably a better idea to declare all `var` s for each scope in one go rather than having two separate `var` declarations.
Mathias Bynens
+3  A: 

This is the only cross-browser-compatible solution AFAIK:

var one = arr[0],
    two = arr[1];
Mathias Bynens
damn. Oh well, thanks
Carson Myers
+2  A: 

CoffeeScript has it: http://jashkenas.github.com/coffee-script/#pattern_matching

And, quoted from the top of the page:

"CoffeeScript is a little language that compiles into JavaScript. Think of it as JavaScript's less ostentatious kid brother — the same genes, roughly the same height, but a different sense of style. Apart from a handful of bonus goodies, statements in CoffeeScript correspond one-to-one with their equivalent in JavaScript, it's just another way of saying it."

Jakob
+1  A: 

You can use array's apply function if you want an array items to be passed as a function arguments.

serious