views:

196

answers:

3

Is there a Javascript equivalen of Perl's qw() method to quickly create arrays ? i.e.

in Perl @myarray = qw / one two three /;
in Javascript var myarray = ('one', 'two', 'three' );  // any alternative??
A: 
var array:Array = [ 1 , 2 , 3 ];
var dictionary:Object = { a:1 , b:2 , c:3 };
drawnonward
it does not compile (in FF at least). I can do var array = [ 1, 2, 3];but not var array = [ one, two, three ].
portoalet
Quote your strings: `var array = [ 'one', 'two', 'three' ]`
Nikki Erwin Ramirez
@Nikki I think the point is that he *doesn't* want to quote every single string.
deceze
In javascript, you have to quote strings unless they are object field names. An array can be initialized with numbers, strings, arrays, or objects.var array:Array = [ 1, "two", [1,2,3], { value:4 }];var dictionary:Object = { one:1, two:"two", three:[1,2,3], four:{value:4}};
drawnonward
+3  A: 

There is not a built in construct, but you can do either of the following:

var myarray = 'one two three'.split(' '); // splits on single spaces

or

function qw (str) {return str.match(/\S+/g)}

var myarray = qw(' one two  three '); // extracts words
Eric Strom
Why `.split(/\s+/)` and not `.split(' ')`? The latter appears to be faster.
Mathias Bynens
@Mathias => Perl's `qw//` operator will split on variable width whitespace. I've updated my answer to include the faster single char split, and a `qw` clone
Eric Strom
@Eric: Cool, I didn’t know `qw//` worked like that. Thanks for your explanation!
Mathias Bynens
+5  A: 

To ‘quickly’ write an array, you can do this:

var x = 'foo bar baz'.split(' ');

Especially for large arrays, this is slightly easier to type than:

var x = ['foo', 'bar', 'baz'];

Although obviously, using .split() is much less performant than just writing out the entire array.

Mathias Bynens
IMHO, the first method is bad form. There's no need to spend unnecessary execution time *every time* the script is ran just to save yourself some key strokes *once*.
Justin Johnson
IMHO, maintainability and readability trumps an extremely minor increase in execution time.
rjh
@Justin Johnson: Exactly! That’s why I recommend typing the whole array out instead.
Mathias Bynens
@rjh What's unmaintainable or unreadable about syntnax as overly common as literal array declaration?
Justin Johnson
@Justin: a qw()-style function is easier to read and, since IE doesn't support trailing commas in literal array declarations, it's easier to add or remove new items without creating a syntax error. Even if the advantages are minimal, I think this kind of syntax optimisation is pointless unless the construct is inside a tight loop.
rjh
IMHO, it's silly to consider array literals anything but easy to read, easy to use, and all-around friendly. Also, using array literals is not an optimization, using a qw-style function is pessimization.
Justin Johnson