Converting an object to a string

后端 未结 30 1893
北荒
北荒 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:31

    In cases where you know the object is just a Boolean, Date, String, number etc... The javascript String() function works just fine. I recently found this useful in dealing with values coming from jquery's $.each function.

    For example the following would convert all items in "value" to a string:

    $.each(this, function (name, value) {
      alert(String(value));
    });
    

    More details here:

    http://www.w3schools.com/jsref/jsref_string.asp

提交回复
热议问题