为什么是“你好,世界!” JavaScript 代码片段被识别为可接受的程序指令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/59837318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:42:18  来源:igfitidea点击:

Why is this "Hello, World!" JavaScript code fragment recognized as an acceptable program instruction?

javascriptnode.js

提问by devaerial

Recently a coworker showed this fragment of JavaScript code:

最近一位同事展示了这段 JavaScript 代码:

greet = "?".toString.bind("hello world!")

If you paste this inside the Developer Console and execute it will print a "Hello, World!" message:

如果您将其粘贴到开发者控制台中并执行,它将打印“Hello, World!” 信息:

>> console.log(greet())
hello, world!

Another interesting thing I found is that if you paste the same greetcode inside Node.js REPL it will automatically transpile it to a "readable" format.

我发现的另一个有趣的事情是,如果您将相同的greet代码粘贴到Node.js REPL 中,它会自动将其转换为“可读”格式。

How does this work? Why is this behaviour possible in a browser and why does Node.js automatically format it?

这是如何运作的?为什么这种行为在浏览器中是可能的,为什么 Node.js 会自动格式化它?

回答by deceze

The actual code is:

实际代码是:

greet = "...".toString.bind("hello world!")

Where the ...in the string literal are the bytes E2 80 AE, which is the right-to-left override Unicode character, which causes everything after it to be displayed in reverse. It's used for writing right-to-left languages like Arabic or Hebrew.

其中...字符串文字中的 是 bytes E2 80 AE,它是从右到左覆盖的 Unicode 字符,这会导致其后的所有内容反向显示。它用于编写从右到左的语言,如阿拉伯语或希伯来语。

hex editors are your friend

十六进制编辑器是你的朋友

回答by feedy

You have hidden characters which reverse the text. Here you can see the raw characters: https://www.soscisurvey.de/tools/view-chars.php

您有反转文本的隐藏字符。在这里你可以看到原始字符:https: //www.soscisurvey.de/tools/view-chars.php

enter image description here

在此处输入图片说明