console.log中的和和+有什么区别? [英] What is the difference between , and + in the console.log?

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

问题描述

pt=new Date(2019,11,12,8,2,3)

console.log(pt.getFullYear()," ",pt.getMonth());

给出结果 2019" 11

console.log(pt.getFullYear()+" "+pt.getMonth());

给出的结果为 2019 11

在此示例中,使用和+有什么区别?

What is the difference between using, and + in this example?

推荐答案

console.log(pt.getFullYear()," ",pt.getMonth());

上面的示例将三个单独的参数传递给console.log.它输出的内容取决于 console.log 的实现方式.随着时间的推移,它已经发生了变化,并且在不同的浏览器之间也没有什么不同.当像示例中那样使用参数调用时,它可以访问变量,并且可以根据类型(例如,它们是数组还是对象)用某种魔术来显示它们.在您的示例中,它显示为:

The above example passes three separate arguments to console.log. What it outputs depends on how console.log is implemented. It has changed over time and is little bit different between browsers. When invoked with arguments like in the example, it has access to the variables and can display them with some magic depending on type, for example if they are arrays or objects. In your example it is displayed as:

2019 " " 11

其中的数字为蓝色文本,表明它是数字类型的变量,空字符串显示为红色,表明这是一个字符串.

where the numbers are in blue text, indicating that it was a variable of type number, and the empty string is shown in red, indicating that is was a string.

将其与以下示例进行比较,其中所有示例在一个参数中传递给 console.log 之前,都已转换为字符串:

Compare this to the following example, where it all is converted to a string before being passed to console.log in one argument:

console.log(pt.getFullYear()+" "+pt.getMonth());

显示为

2017 5

带有黑色文本,表示它是在第一个参数中作为字符串传递的.

with black text, indicating that it was passed as a string in the first parameter.

console.log 的第一个参数可以用作格式字符串,例如c和其他语言的 printf .例如

The first parameter to console.log can be used as a format string, like printf in c and other languages. For example

console.log( "%d %d", pt.getFullYear(), pt.getMonth() );

其中%d是数字的占位符.输出为黑色文本,并提供与第二个示例完全相同的输出.

where %d is a place holder for a number. The output is in black text and gives the exact same output as your second example.

console.log("%d %d", pt.getFullYear(),pt.getMonth(), pt.getDate());

在上面的示例中,年和月将以黑色文本显示,而日期将以蓝色显示.这是因为格式字符串只有两个占位符,但是有三个参数. console.log 使用魔术显示额外的参数.

In the example above, the year and month will be shown in black text, but the date will be in blue. This is because the format string only have two placeholders, but there are three arguments. console.log show the extra arguments, using the magic.

文档:

  • Standard
  • Google Chrome.
  • Mozilla Firefox
  • Microsoft Edge
  • Apple Safari
  • Opera

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

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