javascript 评估
eval('({"suc":true})')
上面的说法是错误的,应该是:
eval('{"suc":true}')
为什么?
eval('({"suc":true})')
The above is wrong,should be:
eval('{"suc":true}')
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当尝试评估时,解释器会看到大括号并认为它是一个块开头。将其括在括号中使其成为表达式并正确初始化对象。
When trying to evaluate the interpreter sees the curly brace and thinks it is a block beginning. Enclosing in parenthesis makes it an expression and initializes an object correctly.
我不知道你想实现什么,但从你的例子来看,第一个是正确的,第二个抛出语法错误。
eval('({"suc":true})')
与({"suc":true})
相同,JavaScript 将其解释为:所以它返回具有
suc
属性和关联值true
的新对象。eval('{"suc":true}')
与{"suc":true}
相同,解释为:如果更改
"suc "
到suc
(不带括号),那么它就可以工作,但它与第一个示例不同。更新:
至于为什么数组不需要括号:JavaSript 中除了数组之外没有其他以
[
字符开头的构造。如果
{
出现在需要这样的值的上下文中,那么它不会有问题:它在源代码中是相同的(因此不仅在 eval 块中):您不能使用短创建对象符号 (
{ .. }
) 而不将其分配给某个变量或作为值传递(到函数、返回语句...)。I don't know what you want to achieve, but from your examples first is correct and the second throws syntax error.
eval('({"suc":true})')
is the same as({"suc":true})
and JavaScript interprets it as:So it returns new object with
suc
property and associated valuetrue
.eval('{"suc":true}')
is the same as{"suc":true}
and is interpreted as:If you change
"suc"
tosuc
(without parentheses), then it would work, but it's not the same as first example.UPDATE:
As to why array doesn't need parentheses: there is no other construct in JavaSript which would start with
[
character other than array.There would be no problem with
{
if it would show up in context which expects value like this:It's the same in source code (so not only in eval block): you can't create object using short notation (
{ .. }
) without assigning it to some variable or passing as value (to function, return statement...).其实这并没有错,会正确评价的。
Thats not wrong actually, it will be evaluated properly.
您是否尝试过使用
JSON.parse('{"suc":true}))
来代替?Have you tried to use
JSON.parse('{"suc":true}))
instead?