简体   繁体   中英

Javascript ES6 console.log object using template literal

I have simple object that I want to display in console

var obj = { name: 'John', age: 22 }

If I type:

console.log(obj)

Object { name: "John", age: 22 }

If I type:

console.log('my object is: ' + obj)

my object is: [object Object]

console.log('my object is: %o', obj)

my object is: Object { name: "John", age: 22 }

How can I achieve this using a template literal?

If I type:

console.log(`my object is: ${obj}`)

my object is: [object Object]

You could serialize the object with JSON.stringify .

 var obj = { name: 'John', age: 22 }; console.log(`my object is: ${JSON.stringify(obj)}`); 

 var obj = { name: 'John', age: 22 } log`This is obj: ${obj}` function log(strings, ...values) { console.log(strings.reduce((p, c, i) => `${p}${c}${values[i]?JSON.stringify(values[i]):''}`, '')); } 

console.log My object is: ${obj} ;

There are tildes(`) at both ends of the grayed section, but the formatting is removing them

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