简体   繁体   English

Python打印与Javascript console.log()

[英]Python print vs Javascript console.log()

In Python: 在Python中:

print [1,2], '\n', [3,4]

would print 会打印

[1,2]
[3,4]

In Javascript: 用Javascript:

console.log([1,2],'\n',[3,4])

prints 版画

[1,2] '\n' [3,4]

What is the equivalent Javascript statement to the above Python print ? 与上面的Python print等效的Javascript语句是什么?

You are sending three arguments to console.log 您正在向console.log发送三个参数

console.log([1,2],'\n',[3,4])

Because the first argument, [1,2] doesn't contain formatting elements (eg %d ), each argument is passed through util.inspect() . 因为第一个参数[1,2]不包含格式元素(例如%d ),所以每个参数都通过util.inspect()传递。 util.inspect is returning the string representation of '\\n' which is not what you want. util.inspect返回的字符串表示形式'\\n'不是您想要的。 You want '\\n' to be interpreted. 您希望对'\\n'进行解释。

One solution is to concatenate all arguments into one string 一种解决方案是将所有参数连接到一个字符串中

> console.log([1,2]+'\n'+[3,4]);
1,2
3,4

Another is to use formatting elements as placeholders, which util.format will substitute with two array's converted values. 另一个方法是使用格式设置元素作为占位符,util.format将用两个数组的转换值代替。

> console.log('%s\n%s', [1,2], [3,4]);
1,2
3,4

I assumed node.js here, but the result in Mozilla is identical. 我在这里假设使用node.js,但是Mozilla中的结果是相同的。

为了安全起见,只需将其拆分为多个console.log调用即可。

Use this: print ([1,2], "\\'\\n'", [3,4]) Here backslash denotes that \\n and ' ' shouldn't perform it's operation and print as it is. 使用以下命令:print([1,2 ,,“ \\'\\ n'”,[3,4])在这里,反斜杠表示\\ n和''不应执行其操作并按原样打印。 Use a \\ before \\n and ' ' 在\\ n和''之前使用\\

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM