Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

javascript - 将对象转换为字符串(Converting an object to a string)

How can I convert a JavaScript object into a string?

(如何将JavaScript对象转换为字符串?)

Example:

(例:)

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

Output:

(输出:)

Object { a=1, b=2} // very nice readable output :)

(对象{a = 1,b = 2} //非常好的可读输出:))


Item: [object Object] // no idea what's inside :(

(Item:[object Object] //不知道里面是什么:()

  ask by user680174 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would recommend using JSON.stringify , which converts the set of the variables in the object to a JSON string.

(我建议使用JSON.stringify ,它将对象中的变量集转换为JSON字符串。)

Most modern browsers support this method natively, but for those that don't, you can include a JS version :

(大多数现代浏览器本机支持此方法,但对于那些不支持此方法的浏览器,您可以包含JS版本 :)

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...