Converting an object to a string

后端 未结 30 2291
北荒
北荒 2020-11-22 03:29

How can I convert a JavaScript object into a string?

Example:

var o = {a:1, b:2}
console.log(o)
console.log(\'Item: \' + o)

Output:

30条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 04:24

    It appears JSON accept the second parameter that could help with functions - replacer, this solves the issue of converting in the most elegant way:

    JSON.stringify(object, (key, val) => {
        if (typeof val === 'function') {
          return String(val);
        }
        return val;
      });
    

提交回复
热议问题