gpt4 book ai didi

javascript - 将某些内容解析为对象文字而不是 block 有什么区别?

转载 作者:行者123 更新时间:2023-11-28 15:08:44 24 4
gpt4 key购买 nike

抱歉,我对 JavaScript 基本概念一无所知。

归结为:

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 中存在非常明显的差异。

我碰巧读到了这篇文章article 。我熟悉函数声明函数表达式之间的区别,以及何时使用其中之一,反之亦然。

来自同一篇文章:

....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

那么,将某些东西解析为对象文字与将它们解析为 block 有什么区别呢?

出于什么目的,我应该考虑在解析的上下文中使用分组字符

最佳答案

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

<小时/>

block 是“表达式组”例如,

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

但是,同样这也是一个 block

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

这意味着当解释器看到 block 符号时,即使您执行类似的操作,它也会假定一个 block

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

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

当您想像这样模糊地编写对象文字时,解决方案是通过提供括号显式强制解释器进入“表达式模式”

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

关于javascript - 将某些内容解析为对象文字而不是 block 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37641192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com