为什么用逗号“"和"+"以不同的方式记录控制台输出? [英] Why comma ' , ' and plus ' + ' log the console output in different pattern?

查看:26
本文介绍了为什么用逗号“"和"+"以不同的方式记录控制台输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用console.log语句进行调试,但是遇到一种情况,在console.log语句中使用','或'+'会以不同的模式记录输出.例如

I am using the console.log statement for debugging , but came across a scenario where using ',' or '+' with console.log statement is logging the output in different pattern.For example

(function() {
  var x = [];
  x.push({
    a: 1,
    b: 2,
  }, {
    a: 4,
    b: 3,
  }, {
    a: 5,
    b: 6
  }, {
    a: 7,
    b: 8,
  })
  console.log('Logging with , ', x);
  console.log('Logging with + ' + x);
}())

当我在console.log中使用','时,我看到的输出为

When I am using ',' with console.log I am seeing output as

Logging with ,  [Object, Object, Object, Object]

每个对象都是可扩展的.但是使用'+'时,我看到的输出为

and each of this object is expandable.But with '+' I am seeing output as

Logging with + [object Object],[object Object],[object Object],[object Object]

为了演示,我创建了这个 jsfiddle .

For demonstration I have created this jsfiddle.

能否请您帮助我理解为什么我们会看到这种差异.

Can you please help me understanding why we see this difference.

推荐答案

+ (字符串连接运算符)与对象将调用 toString 对象上的方法,并返回字符串.因此,''+ object 等同于 object.toString().并且对象上的 toString 返回"[object Object]" .

+(string concatenation operator) with object will call the toString method on the object and a string will be returned. So, '' + object is equivalent to object.toString(). And toString on object returns "[object Object]".

使用 ,该对象作为单独的参数传递到 log 方法.

With , the object is passed as separate argument to the log method.

这篇关于为什么用逗号“"和"+"以不同的方式记录控制台输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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