为什么console.log的行为如下? [英] Why does console.log behave like this?

查看:96
本文介绍了为什么console.log的行为如下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在node.js解释器上: -

On the node.js interpreter:-

console.log("A newline character is written like \"\\ n \".");
//output is:-
// A newline character is written like "\ n ".

但是当你在node.js解释器中输入它时: -

But when you simply enter this in the node.js interpreter:-

"A newline character is written like \"\\ n \"."
// it prints out:-
//'A newline character is written like "\\ n ".'

现在有人为什么会这样?
只是想知道更多关于node.js的信息
提前感谢您的回答。

Does anybody now why this happened? Just curious to know more about node.js Thanks in advance for your answer.

推荐答案

记录 一个字符串时,它会被完全解析并且每个字符被转义,没关系,这是预期的行为。

When logging a string, it gets fully parsed and every character gets escaped, and that's ok, it is the expected behavior.

非正常, 显示字符串(不是记录),解释器试图以最简单的形式显示它。这也可以避免对正在查看它的用户产生任何误解。所以,基本上:

Nonethless, displaying a string (not logging), the interpreter tries to show it in the simplest possible form. This will also avoid any misunderstanding for the user who's looking at it. So, basically:


  • 显示\hi \将显示'hi',因为您可以在单引号分隔的字符串中编写双引号而不转义它,并且它更容易阅读。

  • Displaying "\"hi\"" will show '"hi"', because you can write a double quote inside a single quote delimited string without escaping it, and it's much easier to read.

显示'\'hi \''将显示'hi' ,出于同样的原因。

Displaying '\'hi\'' will show "'hi'", for the same reason.

显示\hi \,'嘿带有单引号和双引号的'强制解释器显示原始字符串(与您创建它的形式相同),因为没有显示它的方式,无论是单引号还是双引号,所以它只能显示为\hi \,'嘿'

Displaying "\"hi\", 'hey'", with both single and double quotes, will force the interpreter to show you the original string (in the same form you created it), because there's no way to display it wothout escaping either the single or the double quotes, so it can only be shown as "\"hi\", 'hey'".

自己动手:

var a = "\"hi\", 'hey'";
> "\"hi\", 'hey'"

var b = "\"hi\"";
> '"hi"'

console.log(a + ", " + b);
> "hi", 'hey', "hi"

这篇关于为什么console.log的行为如下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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