怎么用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.##。