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

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

给定一个对象,任务是使用JavaScript将该对象转换为字符串。有一些方法可以将不同的对象转换为字符串,如下:

将对象转换为字符串的方法

  • 使用String()构造函数
  • 使用JSON.stringify()方法
  • 使用加号(+)操作符与字符串

方法1:使用String()构造函数

该方法将对象的值转换为字符串。

语法:

String(object)  

示例: 在这个示例中,我们将使用string()方法将对象转换为字符串。

// Inputs
let bool_to_s1 = Boolean(0);
let bool_to_s2 = Boolean(1);
let num_to_s = 1234;
 
// Display type of first input
console.log( typeof(bool_to_s1));
 
// After converting to string
console.log( typeof(String(bool_to_s1)));
 
// Display type of first input
console.log( typeof(bool_to_s2));
 
// After converting to string
console.log(typeof(String(bool_to_s2)));
 
// Display type of first input
console.log( typeof(num_to_s));
 
// After converting to string
console.log(typeof(String(num_to_s)));

输出

boolean
string
boolean
string
number
string

方法2:使用JSON.stringify()方法

这个方法将JavaScript对象转换为字符串,用于将数据发送到Web服务器。

语法:

JSON.stringify(obj)  

示例: 在这个示例中,我们将使用 JSON.stringify() 方法 将对象转换为字符串。

// Input object
let obj_to_str = { 
    name: "GeeksForGeeks", 
    city: "Noida", 
    contact: 2488 
};
 
// Converion to string
let myJSON = JSON.stringify(obj_to_str);
 
// Display output
console.log(myJSON);

输出

{"name":"GeeksForGeeks","city":"Noida","contact":2488}

方法3:使用加号(+)操作符与字符串拼接

默认情况下,字符串与任何数据类型的值进行拼接时,会首先将该值转换为字符串类型,然后再将其拼接到字符串中。

语法:

"" + object ;   

示例:

在这个方法中,我们将使用“+”运算符将对象转换为字符串。

// Input objects
let obj1 = new Object();
let obj2 = { ww : 99 , ss : 22};
 
// Display type of objects before
// and after their conversion
console.log( typeof( obj1 ));
console.log( typeof( '' + obj1));
console.log( typeof( obj2 ));
console.log(typeof( '' + obj2 ));

输出

object
string
object
string

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程