Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 将对象转换为字符串的程序

用于将对象转换为字符串的 JavaScript 程序

在本例中,您将学习编写一个将对象转换为字符串的 JavaScript 程序。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 字符串 JavaScript 和 JSON

示例 1: 使用 JSON.stringify() 将对象转换为字符串

// program to convert an object to a string
const person = {
    name: 'Jack',
    age: 27
}
const result =  JSON.stringify(person);
console.log(result);
console.log(typeof result);
输出
{"name":"Jack","age":27}
string
在上面的示例中, JSON.stringify() 方法用于将对象转换为字符串。
typeof 运算符给出了 result 变量的数据类型。

示例 2: 使用 String() 将对象转换为字符串

// program to convert an object to a string
const person = {
    name: 'Jack',
    age: 27
}
const result1 = String(person);
const result2 = String(person['name']);
console.log(result1);
console.log(result2);
console.log(typeof result1);
输出
[object Object]
Jack
string
在上面的示例中, String() 函数将对象的值转换为字符串。
当在 Object 上使用 String() 函数时,转换结果将给出 [object Object]
typeof 运算符给出了 result 变量的数据类型。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4