怎么用js打印出对象

怎么用js打印出对象

首先先说几种解决方法:

1,直接用这个函数

JSON.stringify(value,replace,space)

在这个函数中,一共可以有三个参数,value代表你要带入的对象,后两个参数可写可不写。replace代表你要指定输出的数据。eg:var student=new object();

student.name=lin;

student.age=15;

此时若replace=name,就会直接输出name;

space代表元素之间的分隔符,由你自己定;

代码:

let a=1,b=[1,2,3],c='345',d={a,b,c};
var str=[];
str=JSON.stringify(d);
let str1='I will show you something. This is ' + a + ', and this is ' + b +',and this is ' + c + '.And the last, this is '+ str ;
let str2=`I will show you another thing. This is ${a}, and this is ${b},and this is ${c}.And the last, this is ${str}`;
console.log(str1);
console.log(str2);
console.log('But can you tell me, what the fuck with\"[object Object]\"?');
console.log('And how can I solve this?');




 will show you something. This is 1, and this is 1,2,3,and this is 345.And the last, this is {"a":1,"b":[1,2,3],"c":"345"}
I will show you another thing. This is 1, and this is 1,2,3,and this is 345.And the last, this is {"a":1,"b":[1,2,3],"c":"345"}
But can you tell me, what the fuck with"[object Object]"?
And how can I solve this?

2第二种解决方法:用for语句

代码

let a=1,b=[1,2,3],c='345',d={a,b,c};
var str=[];
for(var i in d){
    str=str+d[i];
    str=str+',';
}
let str1='I will show you something. This is ' + a + ', and this is ' + b +',and this is ' + c + '.And the last, this is '+ str ;
let str2=`I will show you another thing. This is ${a}, and this is ${b},and this is ${c}.And the last, this is ${str}`;
console.log(str1);
console.log(str2);
console.log('But can you tell me, what the fuck with\"[object Object]\"?');
console.log('And how can I solve this?');

结果

I will show you something. This is 1, and this is 1,2,3,and this is 345.And the last, this is 1,1,2,3,345,
I will show you another thing. This is 1, and this is 1,2,3,and this is 345.And the last, this is 1,1,2,3,345,
But can you tell me, what the fuck with"[object Object]"?
And how can I solve this?

解释一下为什么原来的输出是错误的

因为object的prototype链中没有实现自己的tostring()的话,把object转换成string时就会调用object.prototype.tostring,输出格式就会是[object 对象类型].

不能写成console.log('this is a object '+d);但可以写成console.log(d);

js中的类有点像结构体,直接输出时会输出所有的元素,但是要用到它时,就要写成d.##。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值