我正在尝试用 做这样的事情coffescript,但它不起作用..
locations =
  [59.32522, 18.07002]
  [59.327383, 18.06747]
我正在尝试用 做这样的事情coffescript,但它不起作用..
locations =
  [59.32522, 18.07002]
  [59.327383, 18.06747]
哦,我想通了。。
locations = [
  [59.32522, 18.07002]
  [59.327383, 18.06747]
]
我意识到您为自己的问题找到了解决方案,而这并不是您正在寻找柯克的确切答案。但在 Ruby 中有一个我喜欢的任意散列对象散列(注意它们比固定维度数组更占用内存)。
blk = lambda {|h,k| h[k] = Hash.new(&blk)}
x = Hash.new(&blk)
x[:la][:li][:lu][:chunky][:bacon][:foo] = "bar"
这种结构的有趣之处在于,您可以使用它动态创建所需的任何类型的嵌套哈希(有点像使用 mkdir -p 创建子目录)。它与JSON 对象有一些共同点。
让我们看看类似的对象在 CoffeeScript 中会是什么样子
x = 
  la:  
    li:  
      lu:  
        chunky:  
          bacon:  
            foo: 'bar' 
alert x['la']['li']['lu']['chunky']['bacon']['foo']
y = { la: { li: { lu: { chunky: { bacon: { foo:'bary' } } } } } }  
alert y['la']['li']['lu']['chunky']['bacon']['foo']
由于括号运算符不能在 Javascript 中重载,我无法想出比纯 JSON 对象创建更简洁的创建界面
好的,我想出了一个 JSON 语法的缩写,但它不如 Ruby 嵌套哈希好。
Block = (obj,rest...) ->
  console.log 'obj',obj
  console.log 'rest',rest
  obj = {} if (typeof obj is "undefined") 
  if rest.length >= 2
    key = rest[0]
    obj[key] = Block(obj[key],rest[1...]...)
    obj
  else if rest.length is 1
    obj = rest[0]
z = new Block(z,'la','li','lu','chunky','bacon','foo','barz')
console.log z['la']['li']['lu']['chunky']['bacon']['foo']
# extend the object
z = new Block(z,'la','li','lu','chunky','bacon','fooz','ball')
console.log JSON.stringify(z)
# add a node to an internal hash
a = z['la']['li']['lu']
a = new Block(a,'chunky','bacon','another','node')
console.log 'a is',JSON.stringify(a)
# the node now exists on the parent as well
console.log 'z is',JSON.stringify(z)