在 javascript 对象字面量中添加注释

Puttiing comments in javascript object literals

是否可以在 javascript 对象文字中添加注释? 下面的示例在 Firefox 中对我有用,但我找不到任何明确的文档。此外,我看到的所有示例似乎都避免了对象文字中的注释。

  var o = {
    p1: 2,                 // a comment about p1

    /* A comment about function f1 */
    f1: function() { 
      return 3;  
    }
  };

是的,你可以。没有理由不这样做。 JSON 虽然不允许,但不要混淆 JS 和 JSON。

注释几乎可以放在 JavaScript 中的任何地方 - 它们会被解析器忽略。有关评论的更多信息,请参阅 MDN

一些例子...

function test (/* comment where arguments are usually listed */) {}
var obj = /* comment after assignment operator? Why not */ {}
var obj = { prop/* possible, but please don't do this */: 'val' }

请注意,上面的示例并不是真正的好做法 - 我将它们包含在这里只是为了表明可以在 JavaScript 代码中的几乎任何地方添加注释。

The rule of thumb is: If you remove all comments and the result is a valid JavaScript, then you can put a comment there.

区分 JavaScript 和 JSON 也很重要 - 虽然 JSON 的名称中确实有 JavaScript,它与 JavaScript 语法本身无关。 不允许在JSON中发表评论。