将某些东西解析为对象字面而不是块时,它有什么区别? [英] What difference does it makes to parse something as an object literal rather than as a block?

查看:74
本文介绍了将某些东西解析为对象字面而不是块时,它有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我对JavaScript基本概念的无知感到抱歉。

Sorry for my ignorance on JavaScript basic concepts.

归结为:


Literal - 直接在脚本中找到的值。示例:

Literal - A value found directly in the script. Examples:



3.14
"This is a string"
[2, 4, 6]




表达式 - 一组代币,通常文字或标识符,将
与可以评估为特定值的运算符组合在一起。示例:

Expression - A group of tokens, often literals or identifiers, combined with operators that can be evaluated to a specific value. Examples:



2.0
"This is a string"
(x + 2) * 4

在Javascript中,上述两个版本之间存在非常明显的差异。

There is a very clear difference b/w the above two in Javascript.

我碰巧阅读了这篇文章。我熟悉差异b / w 功能声明& 函数表达式以及何时使用其他函数或反之亦然。

I happen to read this article. And I am familiar with the difference b/w function declaration & function expression and when to use one over other or vice-versa.

来自同一篇文章:


....您可能还记得在使用eval评估JSON时,字符串
通常用括号括起来 - eval('( '+ json +')')。这个
当然是出于同样的原因 - 分组运算符,
括号,强制将JSON括号解析为表达式
而不是块:

....You might also recall that when evaluating JSON with eval, the string is usually wrapped with parenthesis — eval('(' + json + ')'). This is of course done for the same reason — grouping operator, which parenthesis are, forces JSON brackets to be parsed as expression rather than as a block:



try {
  { "x": 5 }; // "{" and "}" are parsed as a block
} catch(err) {
  // SyntaxError
}

({ "x": 5 }); // grouping operator forces "{" and "}" to be parsed as object literal

那么,什么除了将它们解析为之外,它是否会将某些内容解析为对象文字

So, what difference does it make to parse something as an object literal other than parsing them as a block?

我应该考虑在分组字符的目的>解析?

And for what purpose should I consider to make use of grouping character, in context of parsing?

推荐答案

首先,不要 eval JSON ,在 String 源上使用 JSON.parse

First, don't eval JSON, use JSON.parse on the String source

一个块是一个表达式组例如,

let x = 0;
if (true) {
    // this is a block
    ++x;
}

然而,同样这也是一个块

However, equally this is also a block

let x = 0;
{ // hi there, I'm a block!
    ++x;
}

这意味着当解释器看到块符号时,即使你有一个块做这样的事情

This means when the interpreter sees block notation, it assumes a block even if you do something like this

{ // this is treated as a block
    foo: ++x
}

这里, foo 充当 label 而不是属性名称,如果您尝试使用尝试的对象文字做更复杂的事情,那么您将获得语法错误

Here, foo acts as a label rather than a property name and if you try to do more complex things with the attempted object literal, you're going to get a Syntax Error.

如果你想像这样模糊地写一个 Object literal ,解决办法是通过提供强制解释器进入表达模式括号

When you want to write an Object literal ambiguously like this, the solution is to force the interpreter into "expression mode" explicitly by providing parenthesis

({ // this is definately an Object literal
    foo: ++x
})

这篇关于将某些东西解析为对象字面而不是块时,它有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆