4

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??

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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.
IMHO, maintainability and readability trumps an extremely minor increase in execution time.
@Justin Johnson: Exactly! That’s why I recommend typing the whole array out instead.
@rjh What's unmaintainable or unreadable about syntnax as overly common as literal array declaration?
@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.
|
5

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

3 Comments

Why .split(/\s+/) and not .split(' ')? The latter appears to be faster.
@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
Cool, I didn’t know qw// worked like that. Thanks for your explanation!
-2
var array:Array = [ 1 , 2 , 3 ];
var dictionary:Object = { a:1 , b:2 , c:3 };

4 Comments

it does not compile (in FF at least). I can do var array = [ 1, 2, 3]; but not var array = [ one, two, three ].
Quote your strings: var array = [ 'one', 'two', 'three' ]
@Nikki I think the point is that he doesn't want to quote every single string.
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}};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.