咖啡脚本:当我尝试创建对象文字的对象文字时,意外的“{”

Coffeescript: Unexpected '{' when I try to create an object literal of object literals

本文关键字:文字 意外 对象 脚本 咖啡 创建对象      更新时间:2023-09-26

对于此语法:

  BASE_RUNNERS = {  basesLoaded:      { first: "manned",  second: "manned", third: "manned" },
                    firstAndSecond:   { first: "manned",  second: "manned", third: "empty"  },
                    firstAndThird:    { first: "manned",  second: "empty",  third: "manned" },
                    secondAndThird:   { first: "empty",   second: "manned", third: "manned" },
                    first:            { first: "manned",  second: "empty",  third: "empty"  },
                    second:           { first: "empty",   second: "manned", third: "empty"  },
                    third:            { first: "empty",   second: "empty",  third: "manned" },
                    empty:            { first: "empty",   second: "empty",  third: "empty"  }
                  }

我收到错误:

[stdin]:154:27: error: unexpected {
                          firstAndSecond:   { first: "manned",  second: "manned", third: "empty",   addedScore: 0 },
                          ^

不知道为什么,这对我来说看起来是合法的。

大括号不是问题,问题是非 CoffeeScript 缩进。CoffeeScript 对空格非常敏感,即使您提供可选的大括号,您仍然需要注意缩进是否与所需的块结构匹配。如果你这样写,混乱就会消失:

BASE_RUNNERS = {
  basesLoaded:      { first: "manned",  second: "manned", third: "manned" },
  firstAndSecond:   { first: "manned",  second: "manned", third: "empty"  },
  firstAndThird:    { first: "manned",  second: "empty",  third: "manned" },
  secondAndThird:   { first: "empty",   second: "manned", third: "manned" },
  first:            { first: "manned",  second: "empty",  third: "empty"  },
  second:           { first: "empty",   second: "manned", third: "empty"  },
  third:            { first: "empty",   second: "empty",  third: "manned" },
  empty:            { first: "empty",   second: "empty",  third: "empty"  }
}

困难的根源是非缩进basesLoaded与其余键的缩进相结合。

Coffeescript 不接受有效的 Javascript 语法,我不得不将其重写为:

 BASE_RUNNERS =
      basesLoaded:    first: "manned", second: "manned", third: "manned"
      firstAndSecond: first: "manned", second: "manned", third: "empty"
      firstAndThird:  first: "manned", second: "empty", third: "manned"
      secondAndThird: first: "empty", second: "manned", third: "manned"
      first:          first: "manned", second: "empty", third: "empty"
      second:         first: "empty", second: "manned", third: "empty"
      third:          first: "empty", second: "empty", third: "manned"
      empty:          first: "empty", second: "empty", third: "empty"

我不确定哪个更好; 恕我直言,看起来更糟。