How to create two arrays in one cycle with CoffeeScript?

I want to create two arrays b and c at the same time. I know two methods that can achieve it. First way:

b = ([i, i * 2] for i in [0..10]) c = ([i, i * 3] for i in [0..10]) alert "b=#{b}" alert "c=#{c}" 

This method is very convenient for creating only one array. I cannot be the best way to get the best performance for computing.

Second method

 b = [] c = [] for i in [0..10] b.push [i, i*2] c.push [i, i*3] alert "b=#{b}" alert "c=#{c}" 

This method seems good for computational efficiency, but the two lines b = [] c = [] should be written first. I do not want to write these 2 lines, but I did not find a good idea to get an answer. Without initialization, we cannot use the push method for arrays b and c.

Is there an existential operator? in Coffeescript, but I don’t know how to use this problem in this problem. Do you have a better method for creating arrays b and c without explicit initialization?

Thanks!

+7
source share
2 answers

You can use a little help from underscore (or any other lib library that provides zip like functionality):

 [b, c] = _.zip ([[i, i * 2], [i, i * 3]] for i in [0..10])... 

After its execution, we have:

 coffee> b [ [ 0, 0 ], [ 1, 2 ], [ 2, 4 ], [ 3, 6 ], [ 4, 8 ], [ 5, 10 ], [ 6, 12 ], [ 7, 14 ], [ 8, 16 ], [ 9, 18 ], [ 10, 20 ] ] coffee> c [ [ 0, 0 ], [ 1, 3 ], [ 2, 6 ], [ 3, 9 ], [ 4, 12 ], [ 5, 15 ], [ 6, 18 ], [ 7, 21 ], [ 8, 24 ], [ 9, 27 ], [ 10, 30 ] ] 

For more information on examples and examples, see the character section in CoffeeScript documents.

+4
source

How about this using the existential operator:

 for i in [0..10] b = [] if not b?.push [i, i*2] c = [] if not c?.push [i, i*3] console.log "b=#{b}" console.log "c=#{c}" 

Or to be more clear:

 for i in [0..10] (if b? then b else b = []).push [i, i*2] (if c? then c else c = []).push [i, i*3] console.log "b=#{b}" console.log "c=#{c}" 

EDIT: from comments:

OK, but you need to write so many tedious codes. For the same reason also for `(b = b or []). push [i, i * 2]

This is tedious, so we can wrap it in a function (but be careful, now the variables will be global):

 # for node.js array = (name) -> global[name] = global[name] or [] # for the browser array = (name) -> window[name] = window[name] or [] for i in [0..10] array('b').push [i, i*2] array('c').push [i, i*3] console.log "b=#{b}" console.log "c=#{c}" 
+1
source

All Articles