0

In CoffeeScript, I declare two different arrays of anonymous objects, and one of them evaluates to an array with a single item, thereby losing data, while the other has multiple items, as it should.

What is going on here, and why would the users variable contain only a single item while the names variable contains multiple items ? Try pasting it here: http://larryng.github.io/coffeescript-repl/ and see.

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"
]

This one does not collapse (with either kind of quotes). Vexing.

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

1 回答 1

2

The first one is turned into 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"
  }
];

so CoffeeScript doesn't see your commas as separating objects inside the array, it sees them more like this:

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

and they're considered to be an optional comma that is supplied rather than being left out.

If you don't indent the commas:

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"
]

then they'll be seen as separators for the three objects you want in your array. Alternatively, put the optional braces in to make the structure very explicit:

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"
}]

or a nice grid (my favorite for small objects like this):

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" }
]

Just because something is (sometimes) optional doesn't mean that you should always leave it out. All the optional things in CoffeeScript introduce ambiguity and CoffeeScript will try to resolve that ambiguity as it sees fit; CoffeeScript also uses whitespace/indentation to express its structure so a one character change in indentation can change your code's structure.

于 2013-10-12T17:03:11.140 回答