为什么{key:value} [" key“]不起作用? [英] why {key:value}["key"] doesn't work?

查看:88
本文介绍了为什么{key:value} [" key“]不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1: {key:value} [key]

2:({key:value}) [key]

我想知道JS解释器如何处理上述代码,以及为什么 1 不起作用以及为什么<强> 2 有效吗?

1:{key:value}["key"]
2:({key:value})["key"]
I'm wondering how the JS interpreter works on the above codes, and why 1 doesn't work and why 2 works?

推荐答案

我假设你问这个问题,因为你在JavaScript REPL(shell)中看到了这个效果。您使用的是一个JavaScript shell,它假定前导{开始一个块语句而不是一个对象文字。

I assume you are asking the question because you saw this effect in a JavaScript REPL (shell). You are using a JavaScript shell which assumes the leading "{" begins a block statement instead of an object literal.

例如,如果您使用随附的JavaScript解释器在Chrome浏览器中,您会看到以下内容:

For example, if you use the JavaScript interpreter that comes with the Chrome browser, you see the following:

> {key:"value"}["key"]
["key"]

在这里,Chrome看到你输入的块语句,然后是一个元素数组的表达式,字符串key。所以它回应了该表达式的结果,即数组 [key]

Here, Chrome saw what you entered as a block statement, followed by the expression that was an array of one element, the string "key". So it responded with the result of that expression, namely the array ["key"]

但不是所有的shell这样工作。如果你将解释器与node.js一起使用,那么#1 为你工作!

But not all shells work this way. If you use the interpreter with node.js, then #1 will work for you!

$ node
> {key:"value"}["key"]
'value'
> 

在像Chrome这样的翻译中,您必须使用括号告诉它您希望第一部分是一个对象文字。 (顺便提一下,这种技术可以在所有 shell中使用,包括节点)。

In interpreters like Chrome, you have to use parentheses to tell it that you want the first part to be an object literal. (This technique, by the way, is guaranteed to work in all shells, including node's).

编辑

正如其中一条评论所指出的,如果你在实际脚本中的任何地方的表达式上下文中使用该构造,它将产生value 。它在shell中的使用看起来令人困惑。

As pointed out in one of the comments, if you use that construct in an expression context anywhere in an actual script, it will produce "value". It's the use in the shell that looks confusing.

这个事实实际上是在着名的 WAT视频

This fact was actually exploited in the famous WAT video by Gary Bernhardt.

这篇关于为什么{key:value} [&quot; key“]不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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