【问题标题】:Putting strings inside objects - javascript将字符串放入对象中 - javascript
【发布时间】:2013-09-20 09:02:42
【问题描述】:

我有一些比下面更复杂的字符串,但简单来说,假设我有

var stats_members = ",\{\"y\"\: 6\}";
var data = 
    [{
                "x": "2012-11-05",
                "y": 6
            },+stats_members+
            ]
          ;

当我console.log(data)我不断收到Uncaught SyntaxError: Unexpected token ] 有人可以解释为什么吗?

【问题讨论】:

  • 你的目标并不明显,在这里。所以很难修复你的代码。
  • 为什么你的数组声明中只有一个操作数的两个+(加法、连接)符号?
  • 也许您想将该字符串评估为一个对象,然后在您的新对象中添加对它的引用,不带加号。
  • @Lepidosteus 因为,实际上我有一些聪明的动态生成的代码。但为了简单起见,我放了一些字符串来测试

标签: javascript string object


【解决方案1】:

正如 cmets 显示的那样,您想要实现的目标尚不清楚。

还有:

},+stats_members+

应该是

},+stats_members

【讨论】:

  • 感谢它的工作!事实上,我有一些聪明的动态生成的代码。但为了简单起见,我放了一些字符串来测试
【解决方案2】:

data变量声明中多了一个'+'

应该是:

var data = [{"x": "2012-11-05", "y": 6 }, stats_members];

【讨论】:

    【解决方案3】:
    var stats_members = ",\{\"y\"\: 6\}";
    var data = 
        [{
                    "x": "2012-11-05",
                    "y": 6
                },+stats_members
                ]
              ;
    

    “stats_members”之后的额外加号导致问题兄弟

    【讨论】:

      【解决方案4】:

      你在那里做了一些非常奇怪的事情。为了让它非常简单,解析器是这样解释你的代码的:

      var data = 
      [                         //-> here starts an array literal
      {                         //-> here starts an object literal (first array item)
        "x": "2012-11-05",      //-> here is the property x in the object literal
        "y": 6                  //-> here is the property y in the object literal
      }                         //-> here ends the object literal
      ,                         //-> comma separating array items
      +stats_members            //-> cast to number by the unary + sign
      +                         //-> add something to the value on the previous row
      ]                         //-> array literal end should not be here, it is expecting something to add
      

      如果您想准确解释您想要做什么,我们可以提供更好的语法帮助。

      【讨论】:

        猜你喜欢
        • 2021-10-15
        • 1970-01-01
        • 2012-09-30
        • 2013-06-15
        • 2015-10-26
        • 2011-12-09
        • 2012-10-11
        • 2017-07-12
        • 1970-01-01
        相关资源
        最近更新 更多