yun*_*_cn 7 javascript arrays push coffeescript
我想同时创建两个数组b和c.我知道有两种方法可以实现它.第一种方法是
b = ([i, i * 2] for i in [0..10])
c = ([i, i * 3] for i in [0..10])
alert "b=#{b}"
alert "c=#{c}"
Run Code Online (Sandbox Code Playgroud)
此方法非常便于创建一个数组.我无法获得更好的计算性能.
第二种方法是
b = []
c = []
for i in [0..10]
b.push [i, i*2]
c.push [i, i*3]
alert "b=#{b}"
alert "c=#{c}"
Run Code Online (Sandbox Code Playgroud)
这种方法似乎对计算效率有好处,但必须首先写入两行b = [] c = [].我不想写这两行,但我没有找到一个好主意得到答案.如果没有b和c数组的初始化,我们就不能使用push方法.
存在运算符存在吗?在Coffeescript但我不知道在这个问题上使用它很热.在没有显式初始化的情况下,您是否有更好的方法来创建b和c的数组?
谢谢!
使用存在运算符怎么样:
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}"
Run Code Online (Sandbox Code Playgroud)
或者更容易理解一点:
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}"
Run Code Online (Sandbox Code Playgroud)
编辑:来自评论:
好吧,但是你必须编写这么多乏味的代码。同样的原因也适用于 ` (b = b 或 []).push [i, i*2]
这很乏味,所以我们可以将它包装在一个函数中(但要注意变量现在将是全局的):
# 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}"
Run Code Online (Sandbox Code Playgroud)