【问题标题】:Array of anonymous objects loses members匿名对象数组失去成员
【发布时间】:2013-10-13 03:31:29
【问题描述】:

在 CoffeeScript 中,我声明了两个不同的匿名对象数组,其中一个评估为一个包含单个项目的数组,从而丢失数据,而另一个则有多个项目,这是它应该的。

这里发生了什么,为什么users 变量只包含一个项目而names 变量包含多个项目?尝试将其粘贴在这里:http://larryng.github.io/coffeescript-repl/ 并查看。

users = [
  username: "Dean"
  email: "xx@yahoo.com"
  password: "spades"
  ,
  username: "Jess"
  email: "xx@yahoo.com"
  password: "spades"
  ,
  username: "Miles"
  email: "xx@yahoo.com"
  password: "spades"
]

这个不会折叠(使用任何一种引号)。烦人。

names = [
   nameA1: 'valueA1'
   nameA2: 'valueA2'
   nameA3: 'valueA3'
  ,
   nameB1: 'valueB1'
   nameB2: 'valueB2'
   nameB3: 'valueB3'
]

【问题讨论】:

  • 我宁愿使用{} 而不是依赖, 的确切缩进。如果 Coffeescript 的某个特性不能使我的代码更具可读性(或可写性),我宁愿不使用它。

标签: arrays coffeescript literals


【解决方案1】:

第一个变成this JavaScript

var users;
users = [
  {
    username: "Dean",
    email: "xx@yahoo.com",
    password: "spades",
    username: "Jess",
    email: "xx@yahoo.com",
    password: "spades",
    username: "Miles",
    email: "xx@yahoo.com",
    password: "spades"
  }
];

因此,CoffeeScript 不会将逗号视为数组内的分隔对象,而是将它们视为这样:

users = [
  username: "Dean"
  email: "xx@yahoo.com"
  password: "spades",
  # ----------------^

它们被认为是一个可选的逗号,被提供而不是被忽略。

如果你不缩进逗号:

users = [
  username: "Dean"
  email: "xx@yahoo.com"
  password: "spades"
,
  username: "Jess"
  email: "xx@yahoo.com"
  password: "spades"
,
  username: "Miles"
  email: "xx@yahoo.com"
  password: "spades"
]

然后它们将被视为数组中您想要的三个对象的分隔符。或者,放入可选的大括号以使结构非常明确:

users = [{
    username: "Dean"
    email: "xx@yahoo.com"
    password: "spades"
  }, {
    username: "Jess"
    email: "xx@yahoo.com"
    password: "spades"
  }, {
    username: "Miles"
    email: "xx@yahoo.com"
    password: "spades"
}]

或一个漂亮的网格(我最喜欢这样的小物体):

users = [
  { username: "Dean",  email: "xx@yahoo.com", password: "spades" },
  { username: "Jess",  email: "xx@yahoo.com", password: "spades" },
  { username: "Miles", email: "xx@yahoo.com", password: "spades" }
]

仅仅因为某些东西(有时)是可选的,并不意味着您应该始终将其排除在外。 CoffeeScript 中所有可选的东西都会引入歧义,CoffeeScript 将尝试在它认为合适的时候解决这种歧义; CoffeeScript 还使用空格/缩进来表达其结构,因此缩进中一个字符的变化可以改变您的代码结构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    相关资源
    最近更新 更多