第一個變成this JavaScript:
var users;
users = [
{
username: "Dean",
email: "[email protected]",
password: "spades",
username: "Jess",
email: "[email protected]",
password: "spades",
username: "Miles",
email: "[email protected]",
password: "spades"
}
];
所以CoffeeScript中沒有看到您的逗號作爲數組裏面分離對象的,它看到他們更多的是這樣的:
users = [
username: "Dean"
email: "[email protected]"
password: "spades",
# ----------------^
,它們被認爲是一個可選的逗號,而不是被遺漏。
如果不縮進逗號:
users = [
username: "Dean"
email: "[email protected]"
password: "spades"
,
username: "Jess"
email: "[email protected]"
password: "spades"
,
username: "Miles"
email: "[email protected]"
password: "spades"
]
那麼他們就會被看作是分隔符爲您在陣列中所需的三個對象。或者,把可選的括號中,使結構非常明確:
users = [{
username: "Dean"
email: "[email protected]"
password: "spades"
}, {
username: "Jess"
email: "[email protected]"
password: "spades"
}, {
username: "Miles"
email: "[email protected]"
password: "spades"
}]
或者一個漂亮的網格(我最喜歡這樣的小物件):
users = [
{ username: "Dean", email: "[email protected]", password: "spades" },
{ username: "Jess", email: "[email protected]", password: "spades" },
{ username: "Miles", email: "[email protected]", password: "spades" }
]
只因爲出現(有時)可選並不意味着你應該永遠不要離開它。 CoffeeScript中所有可選的東西都引入了歧義,CoffeeScript將嘗試根據它認爲合適的方式解決這種模糊性; CoffeeScript還使用空格/縮進來表示其結構,因此縮進中的一個字符更改可以更改您的代碼結構。
我寧願使用'{}'而不是依賴''的確切縮進。如果Coffeescript的功能不會使我的代碼更具可讀性(或可寫),我寧願不使用它。 – hpaulj