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?
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?
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.
This is the only cross-browser-compatible solution AFAIK:
var one = arr[0],
two = arr[1];
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."
You can use array's apply function if you want an array items to be passed as a function arguments.