简体   繁体   中英

Python print vs Javascript console.log()

In Python:

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

would print

[1,2]
[3,4]

In 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 ?

You are sending three arguments to 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() . util.inspect is returning the string representation of '\\n' which is not what you want. You want '\\n' to be interpreted.

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.

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

为了安全起见,只需将其拆分为多个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. Use a \\ before \\n and ' '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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